import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SolutionDesignSchema } from '@/server/modules/solution-designs/solution-design.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { SolutionDesignService } from '@/server/modules/solution-designs/solution-design.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 查询参数Schema
const ListQuery = z.object({
  page: z.coerce.number().int().positive().default(1).openapi({
    description: '页码',
    example: 1
  }),
  pageSize: z.coerce.number().int().positive().default(10).openapi({
    description: '每页条数',
    example: 10
  }),
  status: z.string().optional().openapi({
    description: '状态过滤：draft, reviewing, completed',
    example: 'completed'
  })
});

// 响应Schema
const ListResponse = z.object({
  data: z.array(SolutionDesignSchema),
  pagination: z.object({
    total: z.number().openapi({ example: 100, description: '总记录数' }),
    current: z.number().openapi({ example: 1, description: '当前页码' }),
    pageSize: z.number().openapi({ example: 10, description: '每页数量' })
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: ListQuery
  },
  responses: {
    200: {
      description: '成功获取方案设计列表',
      content: { 'application/json': { schema: ListResponse } }
    },
    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 user = c.get('user');
    
    const service = new SolutionDesignService(AppDataSource);
    const [data, total] = await service.getUserSolutionDesigns(
      user.id,
      query.page,
      query.pageSize,
      query.status
    );

    return c.json({
      data,
      pagination: {
        total,
        current: query.page,
        pageSize: query.pageSize
      }
    }, 200);

  } catch (error) {
    console.error('获取方案设计列表失败:', error);
    const { code = 500, message = '获取列表失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;