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 { PrinterService } from '../../services/printer.service';
import { getFeieApiConfig } from '../utils/feie-config.util';

// 打印机详情路由参数Schema
const PrinterDetailParamsSchema = z.object({
  printerSn: z.string()
});

// 打印机详情响应Schema
const PrinterDetailResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    id: z.number(),
    tenantId: z.number(),
    printerSn: z.string(),
    printerName: z.string().nullable(),
    printerKey: z.string(),
    printerType: z.enum(['58mm', '80mm']),
    printerStatus: z.enum(['ACTIVE', 'INACTIVE', 'ERROR']),
    isDefault: z.number(),
    createdAt: z.string(),
    updatedAt: z.string()
  })
});

// 打印机详情路由定义
const printerDetailRoute = createRoute({
  method: 'get',
  path: '/:printerSn',
  middleware: [authMiddleware],
  request: {
    params: PrinterDetailParamsSchema
  },
  responses: {
    200: {
      description: '打印机详情获取成功',
      content: { 'application/json': { schema: PrinterDetailResponseSchema } }
    },
    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() }) } }
    },
    404: {
      description: '打印机不存在',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    }
  }
});

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

    // 获取飞鹅API配置
    const feieConfig = await getFeieApiConfig(tenantId, AppDataSource);
    if (!feieConfig) {
      return c.json({ success: false, message: '飞鹅API配置未找到或配置不完整' }, 400);
    }

    // 创建带配置的服务实例
    const printerService = new PrinterService(AppDataSource, feieConfig);
    const printer = await printerService.repository.findOne({
      where: { tenantId, printerSn } as any
    });

    if (!printer) {
      return c.json({ success: false, message: '打印机不存在' }, 404);
    }

    // 转换Date对象为ISO字符串
    const transformedPrinter = {
      ...printer,
      createdAt: printer.createdAt.toISOString(),
      updatedAt: printer.updatedAt.toISOString()
    };

    // 验证响应格式
    const validatedResponse = await parseWithAwait(PrinterDetailResponseSchema, {
      success: true,
      data: transformedPrinter
    });

    return c.json(validatedResponse, 200);
  });

export default app;