import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { SettingValueResponse } 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 GetParams = z.object({
  key: z.string().openapi({
    param: { name: 'key', in: 'path' },
    example: 'home_register_enabled',
    description: '设置键名'
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'get',
  path: '/{key}',
  middleware: [authMiddleware],
  request: {
    params: GetParams
  },
  responses: {
    200: {
      description: '成功获取系统设置值',
      content: { 'application/json': { schema: SettingValueResponse } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '设置不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 路由实现
const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  try {
    const { key } = c.req.valid('param');
    const service = new SystemSettingService(AppDataSource);
    const setting = await service.findByKey(key);
    
    if (!setting) {
      return c.json({ code: 404, message: `设置 ${key} 不存在` }, 404);
    }

    return c.json({
      settingKey: setting.settingKey,
      settingValue: setting.settingValue,
      description: setting.description,
      settingType: setting.settingType
    }, 200);
  } catch (error) {
    const { code = 500, message = '获取系统设置失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;