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 } from '../../types/feie.types';

// 打印任务列表查询参数Schema
const PrintTaskListQuerySchema = z.object({
  page: z.string().optional().transform(val => val ? parseInt(val, 10) : 1),
  pageSize: z.string().optional().transform(val => val ? parseInt(val, 10) : 20),
  orderId: z.string().optional().transform(val => val ? parseInt(val, 10) : undefined),
  printerSn: z.string().optional(),
  printType: z.enum(['RECEIPT', 'SHIPPING', 'ORDER', 'ALL']).optional().default('ALL').transform(val => val === 'ALL' ? undefined : val as PrintType),
  status: z.enum(['PENDING', 'DELAYED', 'PRINTING', 'SUCCESS', 'FAILED', 'CANCELLED', 'ALL']).optional().default('ALL').transform(val => val === 'ALL' ? undefined : val as PrintStatus),
  startDate: z.string().optional().transform(val => val ? new Date(val) : undefined),
  endDate: z.string().optional().transform(val => val ? new Date(val) : undefined),
  search: z.string().optional()
});

// 打印任务列表响应Schema
const PrintTaskListResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    data: z.array(z.object({
      id: z.number(),
      taskId: z.string(),
      tenantId: z.number(),
      printerSn: z.string(),
      orderId: z.number().nullable(),
      printType: z.nativeEnum(PrintType),
      content: z.string(),
      printStatus: z.nativeEnum(PrintStatus),
      errorMessage: z.string().nullable(),
      retryCount: z.number(),
      maxRetries: z.number(),
      scheduledAt: z.string().nullable(),
      printedAt: z.string().nullable(),
      cancelledAt: z.string().nullable(),
      createdAt: z.string(),
      updatedAt: z.string()
    })),
    total: z.number(),
    page: z.number(),
    pageSize: z.number()
  })
});

// 打印任务列表路由定义
const printTaskListRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: PrintTaskListQuerySchema
  },
  responses: {
    200: {
      description: '打印任务列表获取成功',
      content: { 'application/json': { schema: PrintTaskListResponseSchema } }
    },
    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(printTaskListRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;

    try {
      const query = c.req.valid('query');
      const filters = {
        orderId: query.orderId,
        printerSn: query.printerSn,
        printType: query.printType,
        printStatus: query.status,
        startDate: query.startDate,
        endDate: query.endDate,
        search: query.search
      };
      const page = query.page;
      const limit = query.pageSize;

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

      // 创建带配置的打印任务服务实例
      const printTaskService = new PrintTaskService(AppDataSource, feieConfig);
      const result = await printTaskService.getPrintTasks(tenantId, filters, page, limit);

      // 转换Date对象为ISO字符串
      const transformedTasks = result.tasks.map(task => ({
        ...task,
        createdAt: task.createdAt.toISOString(),
        updatedAt: task.updatedAt.toISOString(),
        scheduledAt: task.scheduledAt ? task.scheduledAt.toISOString() : null,
        printedAt: task.printedAt ? task.printedAt.toISOString() : null,
        cancelledAt: task.cancelledAt ? task.cancelledAt.toISOString() : null
      }));

      // 验证响应格式
      const response = {
        success: true as const,
        data: {
          data: transformedTasks,
          total: result.total,
          page,
          pageSize: limit
        }
      };
      const validatedResponse = await parseWithAwait(PrintTaskListResponseSchema, response);

      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;