import { createRoute, OpenAPIHono } 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 { CreateSystemConfigSchema, SystemConfigSchema } from '../../schemas/system-config.schema.mt';

const createSystemConfigRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: CreateSystemConfigSchema
        }
      }
    }
  },
  responses: {
    201: {
      description: '系统配置创建成功',
      content: {
        'application/json': {
          schema: SystemConfigSchema
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器内部错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const createSystemConfigRoutes = new OpenAPIHono<AuthContext>()
  // 创建系统配置路由
  .openapi(createSystemConfigRoute, async (c) => {
    const data = c.req.valid('json');
    const user = c.get('user');

    try {
      const systemConfigService = new SystemConfigServiceMt(AppDataSource);

      // 使用setConfig方法，它会自动处理缓存刷新
      const result = await systemConfigService.setConfig(
        data.configKey,
        data.configValue,
        user.tenantId,
        data.description || undefined
      );

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

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

export default createSystemConfigRoutes;