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';

// 打印任务详情参数Schema
const PrintTaskDetailParamsSchema = z.object({
  taskId: z.string().min(1, '任务ID不能为空')
});

// 打印任务详情响应Schema
const PrintTaskDetailResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    id: z.number(),
    tenantId: z.number(),
    taskId: z.string(),
    orderId: z.number().nullable(),
    printerSn: z.string(),
    content: z.string(),
    printType: z.enum(['RECEIPT', 'SHIPPING', 'ORDER']),
    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 printTaskDetailRoute = createRoute({
  method: 'get',
  path: '/:taskId',
  middleware: [authMiddleware],
  request: {
    params: PrintTaskDetailParamsSchema
  },
  responses: {
    200: {
      description: '打印任务详情获取成功',
      content: { 'application/json': { schema: PrintTaskDetailResponseSchema } }
    },
    404: {
      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(printTaskDetailRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { taskId } = c.req.valid('param');

    // 创建打印任务服务实例（使用默认配置，因为只需要查询数据库）
    const printTaskService = new PrintTaskService(AppDataSource, {
      baseUrl: 'https://api.feieyun.cn/Api/Open/',
      user: '',
      ukey: '',
      timeout: 10000,
      maxRetries: 3
    });

    const task = await printTaskService.repository.findOne({
      where: { tenantId, taskId } as any
    });

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

    // 验证响应格式
    const response = {
      success: true as const,
      data: {
        id: task.id,
        tenantId: task.tenantId,
        taskId: task.taskId,
        orderId: task.orderId,
        printerSn: task.printerSn,
        content: task.content,
        printType: task.printType,
        printStatus: task.printStatus,
        errorMessage: task.errorMessage,
        retryCount: task.retryCount,
        maxRetries: task.maxRetries,
        scheduledAt: task.scheduledAt ? task.scheduledAt.toISOString() : null,
        printedAt: task.printedAt ? task.printedAt.toISOString() : null,
        cancelledAt: task.cancelledAt ? task.cancelledAt.toISOString() : null,
        cancelReason: task.cancelReason,
        createdAt: task.createdAt.toISOString(),
        updatedAt: task.updatedAt.toISOString()
      }
    };
    const validatedResponse = await parseWithAwait(PrintTaskDetailResponseSchema, response);

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

export default app;