import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { TemplateSchema } from '@/server/modules/templates/template.schema';
import { AppDataSource } from '@/server/data-source';
import { TemplateService } from '@/server/modules/templates/template.service';

// 查询参数Schema
const ListQuery = z.object({
  page: z.coerce.number().int().positive().default(1).openapi({
    description: '页码',
    example: 1
  }),
  pageSize: z.coerce.number().int().positive().max(100).default(12).openapi({
    description: '每页条数',
    example: 12
  }),
  category: z.string().optional().openapi({
    description: '分类筛选',
    example: '合同'
  }),
  isFree: z.coerce.number().int().min(0).max(1).optional().openapi({
    description: '是否免费',
    example: 1
  })
});

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

// 路由定义
const listRoute = createRoute({
  method: 'get',
  path: '/',
  request: {
    query: ListQuery
  },
  responses: {
    200: {
      description: '成功获取模板列表',
      content: { 'application/json': { schema: ListResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ code: z.number(), message: z.string() }) } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono().openapi(listRoute, async (c) => {
  try {
    const query = c.req.valid('query');
    const service = new TemplateService(AppDataSource);
    
    const [data, total] = await service.getAvailableTemplates(
      query.page,
      query.pageSize,
      query.category,
      query.isFree !== undefined ? Boolean(query.isFree) : undefined
    );
    
    return c.json({
      data,
      pagination: {
        total,
        current: query.page,
        pageSize: query.pageSize
      }
    }, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '获取模板列表失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;