import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { ChatMessageSchema, HistoryQuerySchema } from '@/server/modules/chat/chat-message.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { ChatMessageService } from '@/server/modules/chat/chat-message.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';
import { parseWithAwait } from '@/server/utils/parseWithAwait';

// 历史消息查询路由
const routeDef = createRoute({
  method: 'get',
  path: '/history',
  middleware: [authMiddleware],
  request: {
    query: HistoryQuerySchema
  },
  responses: {
    200: {
      description: '成功获取聊天历史',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(ChatMessageSchema),
            pagination: z.object({
              total: z.number().openapi({ example: 100, description: '总记录数' }),
              current: z.number().openapi({ example: 1, description: '当前页码' }),
              pageSize: z.number().openapi({ example: 50, description: '每页数量' })
            })
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const query = c.req.valid('query');
    const { classId, page, pageSize } = query;
    
    const chatMessageService = new ChatMessageService(AppDataSource);
    const [data, total] = await chatMessageService.getHistoryByClassId(
      classId,
      page,
      pageSize
    );
    
    return c.json({
      data: await parseWithAwait(z.array(ChatMessageSchema), data),
      pagination: {
        total,
        current: page,
        pageSize
      }
    }, 200);
  } catch (error) {
    return c.json({
      code: 500,
      message: error instanceof Error ? error.message : '获取聊天历史失败'
    }, 500);
  }
});

export default app;