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 UpdateParams = z.object({
  key: z.string().openapi({
    param: { name: 'key', in: 'path' },
    example: 'home_register_enabled',
    description: '设置键名'
  })
});

// 请求体Schema
const UpdateValueRequest = z.object({
  settingValue: z.string().nullable().openapi({
    description: '设置值',
    example: 'false'
  })
});

// 路由定义
const routeDef = createRoute({
  method: 'put',
  path: '/{key}',
  middleware: [authMiddleware],
  request: {
    params: UpdateParams,
    body: {
      content: {
        'application/json': { schema: UpdateValueRequest }
      }
    }
  },
  responses: {
    200: {
      description: '成功更新系统设置',
      content: { 'application/json': { schema: SystemSettingSchema } }
    },
    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 { settingValue } = await c.req.json();
    
    const service = new SystemSettingService(AppDataSource);
    const setting = await service.updateValue(key, settingValue);
    
    return c.json(setting, 200);
  } catch (error) {
    const { code = 500, message = '更新系统设置失败' } = error as Error & { code?: number };
    return c.json({ code, message }, code);
  }
});

export default app;