import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SystemSettingSchema } from '@/server/modules/settings/system-setting.schema';
import { ErrorSchema } from '@/server/utils/errorHandler';
import { AppDataSource } from '@/server/data-source';
import { SystemSettingService } from '@/server/modules/settings/system-setting.service';
import { AuthContext } from '@/server/types/context';
import { authMiddleware } from '@/server/middleware/auth.middleware';

// 响应Schema
const ListResponse = z.object({
  data: z.array(SystemSettingSchema),
  total: z.number().openapi({ example: 10, description: '总记录数' })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  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 service = new SystemSettingService(AppDataSource);
    const data = await service.findAll();
    
    return c.json({
      data,
      total: data.length
    }, 200);
  } catch (error) {
    const { code = 500, message = '获取系统设置列表失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;