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 { PrintTaskService } from '../../services/print-task.service';
import { getFeieApiConfig } from '../utils/feie-config.util';
import { PrintType, PrintStatus, CreatePrintTaskDto } from '../../types/feie.types';

// 打印任务创建请求Schema
const PrintTaskCreateRequestSchema = z.object({
  printerSn: z.string().min(1, '打印机SN不能为空'),
  orderId: z.number().optional(),
  printType: z.nativeEnum(PrintType).default(PrintType.RECEIPT),
  content: z.string().min(1, '打印内容不能为空'),
  copies: z.number().min(1).max(10).default(1),
  priority: z.enum(['HIGH', 'NORMAL', 'LOW']).default('NORMAL')
});

// 打印任务创建响应Schema
const PrintTaskCreateResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    taskId: z.string(),
    tenantId: z.number(),
    printerSn: z.string(),
    orderId: z.number().nullable(),
    printType: z.enum(['RECEIPT', 'SHIPPING', 'ORDER']),
    content: z.string(),
    printStatus: z.enum(['PENDING', 'DELAYED', 'PRINTING', 'SUCCESS', 'FAILED', 'CANCELLED']),
    errorMessage: z.string().nullable(),
    retryCount: z.number(),
    maxRetries: z.number(),
    scheduledAt: z.string().nullable(),
    printedAt: z.string().nullable(),
    cancelledAt: z.string().nullable(),
    cancelReason: z.string().nullable(),
    createdAt: z.string(),
    updatedAt: z.string()
  })
});

// 打印任务创建路由定义
const printTaskCreateRoute = createRoute({
  method: 'post',
  path: '/',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: PrintTaskCreateRequestSchema }
      }
    }
  },
  responses: {
    200: {
      description: '打印任务创建成功',
      content: { 'application/json': { schema: PrintTaskCreateResponseSchema } }
    },
    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(printTaskCreateRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    try {
      const body = c.req.valid('json');

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

      // 创建带配置的打印任务服务实例
      const printTaskService = new PrintTaskService(AppDataSource, feieConfig);

      // 转换请求体为CreatePrintTaskDto
      const taskDto: CreatePrintTaskDto = {
        printerSn: body.printerSn,
        orderId: body.orderId,
        printType: body.printType,
        content: body.content,
        delaySeconds: 0 // 默认不延迟
      };

      const task = await printTaskService.createPrintTask(tenantId, taskDto);

      // 转换Date字段为ISO字符串格式
      const taskResponse = {
        ...task,
        scheduledAt: task.scheduledAt ? task.scheduledAt.toISOString() : null,
        printedAt: task.printedAt ? task.printedAt.toISOString() : null,
        cancelledAt: task.cancelledAt ? task.cancelledAt.toISOString() : null,
        createdAt: task.createdAt.toISOString(),
        updatedAt: task.updatedAt.toISOString()
      };

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

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 创建打印任务失败:`, error);
      const errorMessage = error instanceof Error ? error.message : '创建打印任务失败';
      return c.json({ success: false, message: errorMessage }, 500);
    }
  });

export default app;