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

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

const deleteSystemConfigRoutes = new OpenAPIHono<AuthContext>()
  // 删除系统配置路由
  .openapi(deleteSystemConfigRoute, async (c) => {
    const { id } = c.req.valid('param');

    try {
      const systemConfigService = new SystemConfigService(AppDataSource);

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

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

      return c.body(null, 204);
    } catch (error) {
      console.error('删除系统配置失败:', error);
      return c.json(
        { code: 500, message: error instanceof Error ? error.message : '删除系统配置失败' },
        500
      );
    }
  });

export default deleteSystemConfigRoutes;