import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { authMiddleware } from '../../../../auth-module-mt/src/middleware/index.mt';
import { AppDataSource, parseWithAwait, ErrorSchema } from '@d8d/shared-utils';
import { AuthContext } from '@d8d/shared-types';
import { SystemConfigServiceMt } from '../../services/system-config.service.mt';
import { UpdateSystemConfigSchema, SystemConfigSchema } from '../../schemas/system-config.schema.mt';

const updateSystemConfigRoute = createRoute({
  method: 'put',
  path: '/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number<number>().openapi({
        description: '系统配置ID',
        example: 1
      })
    }),
    body: {
      content: {
        'application/json': {
          schema: UpdateSystemConfigSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '系统配置更新成功',
      content: {
        'application/json': {
          schema: SystemConfigSchema
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '系统配置不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器内部错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const updateSystemConfigRoutes = new OpenAPIHono<AuthContext>()
  // 更新系统配置路由
  .openapi(updateSystemConfigRoute, async (c) => {
    const { id } = c.req.valid('param');
    const data = c.req.valid('json');

    try {
      const systemConfigService = new SystemConfigServiceMt(AppDataSource);

      // 使用update方法，它会自动处理缓存刷新
      const result = await systemConfigService.update(id, data);

      if (!result) {
        return c.json({ code: 404, message: '系统配置不存在' }, 404);
      }

      // 验证响应格式
      const validatedResult = await parseWithAwait(SystemConfigSchema, result);

      return c.json(validatedResult, 200);
    } catch (error) {
      console.error('更新系统配置失败:', error);
      return c.json(
        { code: 500, message: error instanceof Error ? error.message : '更新系统配置失败' },
        500
      );
    }
  });

export default updateSystemConfigRoutes;