import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';
import { ConfigService } from '../../services/config.service';

// 更新打印配置参数Schema
const UpdatePrintConfigParamsSchema = z.object({
  configKey: z.string().min(1, '配置键不能为空')
});

// 更新打印配置请求体Schema
const UpdatePrintConfigBodySchema = z.object({
  configValue: z.string().min(1, '配置值不能为空')
});

// 更新打印配置响应Schema
const UpdatePrintConfigResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    id: z.number(),
    tenantId: z.number(),
    configKey: z.string(),
    configValue: z.string(),
    configType: z.enum(['STRING', 'JSON', 'BOOLEAN', 'NUMBER']),
    description: z.string().nullable(),
    createdAt: z.string(),
    updatedAt: z.string()
  })
});

// 更新打印配置路由定义
const updatePrintConfigRoute = createRoute({
  method: 'put',
  path: '/:configKey',
  middleware: [authMiddleware],
  request: {
    params: UpdatePrintConfigParamsSchema,
    body: {
      content: {
        'application/json': { schema: UpdatePrintConfigBodySchema }
      }
    }
  },
  responses: {
    200: {
      description: '打印配置更新成功',
      content: { 'application/json': { schema: UpdatePrintConfigResponseSchema } }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(updatePrintConfigRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { configKey } = c.req.valid('param');
    const { configValue } = c.req.valid('json');

    if (!configValue) {
      return c.json({ success: false, message: '配置值不能为空' }, 400);
    }

    try {
      const configService = new ConfigService(AppDataSource);
      const config = await configService.updatePrintConfig(tenantId, configKey, configValue);

      // 将 FeieConfigMt 转换为前端需要的格式
      const transformedConfig = {
        id: config.id,
        tenantId: config.tenantId,
        configKey: config.configKey,
        configValue: config.configValue || '',
        configType: config.configType as 'STRING' | 'JSON' | 'BOOLEAN' | 'NUMBER',
        description: config.description || null,
        createdAt: config.createdAt.toISOString(),
        updatedAt: config.updatedAt.toISOString()
      };

      // 验证响应格式
      const response = {
        success: true as const,
        data: transformedConfig
      };
      const validatedResponse = await parseWithAwait(UpdatePrintConfigResponseSchema, response);

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 更新配置失败，key: ${configKey}:`, error);
      return c.json({ success: false, message: '更新配置失败' }, 500);
    }
  });

export default app;