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

// 查询参数Schema
const PopularQuery = z.object({
  limit: z.coerce.number().int().positive().max(20).default(8).openapi({
    description: '获取数量',
    example: 8
  })
});

// 路由定义
const popularRoute = createRoute({
  method: 'get',
  path: '/popular',
  request: {
    query: PopularQuery
  },
  responses: {
    200: {
      description: '成功获取热门模板',
      content: { 
        'application/json': { 
          schema: z.array(z.any()) // 使用TemplateSchema数组
        } 
      }
    },
    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(popularRoute, async (c) => {
  try {
    const query = c.req.valid('query');
    const service = new TemplateService(AppDataSource);
    const templates = await service.getPopularTemplates(query.limit);
    return c.json(templates, 200);
  } catch (error) {
    const message = error instanceof Error ? error.message : '获取热门模板失败';
    return c.json({ code: 500, message }, 500);
  }
});

export default app;