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 PrinterStatusParamsSchema = z.object({
  printerSn: z.string()
});

// 打印机状态响应Schema
const PrinterStatusResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    printerSn: z.string(),
    printerName: z.string().nullable(),
    printerStatus: z.enum(['ONLINE', 'OFFLINE', 'ERROR']),
    paperStatus: z.enum(['NORMAL', 'LOW', 'EMPTY']).optional(),
    temperature: z.number().optional(),
    printCount: z.number().optional(),
    lastPrintTime: z.string().optional(),
    lastCheckTime: z.string()
  })
});

// 打印机状态查询路由定义
const printerStatusRoute = createRoute({
  method: 'get',
  path: '/:printerSn/status',
  middleware: [authMiddleware],
  request: {
    params: PrinterStatusParamsSchema
  },
  responses: {
    200: {
      description: '打印机状态获取成功',
      content: { 'application/json': { schema: PrinterStatusResponseSchema } }
    },
    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(printerStatusRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { printerSn } = c.req.valid('param');

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

      // 创建带配置的服务实例
      const printerService = new PrinterService(AppDataSource, feieConfig);
      const status = await printerService.getPrinterStatus(tenantId, printerSn);

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

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 查询打印机状态失败，打印机SN: ${printerSn}:`, error);
      const errorMessage = error instanceof Error ? error.message : '查询打印机状态失败';
      return c.json({ success: false, message: errorMessage }, 500);
    }
  });

export default app;