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 PrintConfigListResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    data: z.array(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 printConfigListRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  responses: {
    200: {
      description: '打印配置列表获取成功',
      content: { 'application/json': { schema: PrintConfigListResponseSchema } }
    },
    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(printConfigListRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    try {
      const configService = new ConfigService(AppDataSource);
      const configs = await configService.getPrintConfigs(tenantId);

      // 将 FeieConfigMt 转换为前端需要的格式
      const transformedConfigs = configs.map(config => ({
        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 validatedResponse = await parseWithAwait(PrintConfigListResponseSchema, {
        success: true,
        data: {
          data: transformedConfigs
        }
      });

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 获取打印配置失败:`, error);
      return c.json({ success: false, message: '获取打印配置失败' }, 500);
    }
  });

export default app;