import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource } 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';

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

// 打印任务状态响应Schema
const PrintTaskStatusResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    taskId: z.string(),
    printStatus: z.enum(['PENDING', 'DELAYED', 'PRINTING', 'SUCCESS', 'FAILED', 'CANCELLED']),
    feieStatus: z.string().optional(),
    errorMessage: z.string().nullable(),
    retryCount: z.number(),
    printedAt: z.string().nullable(),
    lastCheckedAt: z.string().optional()
  })
});

// 打印任务状态路由定义
const printTaskStatusRoute = createRoute({
  method: 'get',
  path: '/:taskId/status',
  middleware: [authMiddleware],
  request: {
    params: PrintTaskStatusParamsSchema
  },
  responses: {
    200: {
      description: '打印任务状态获取成功',
      content: { 'application/json': { schema: PrintTaskStatusResponseSchema } }
    },
    400: {
      description: '配置错误',
      content: { 'application/json': { schema: z.object({ success: z.boolean(), message: z.string() }) } }
    },
    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(printTaskStatusRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { taskId } = c.req.valid('param');

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

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

      return c.json({
        success: true,
        data: {
          taskId: status.taskId,
          printStatus: status.printStatus,
          feieStatus: status.feieStatus,
          errorMessage: status.errorMessage,
          retryCount: status.retryCount,
          printedAt: status.printedAt ? status.printedAt.toISOString() : null,
          lastCheckedAt: status.lastCheckedAt ? status.lastCheckedAt.toISOString() : undefined
        }
      }, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 获取打印任务状态失败，任务ID: ${taskId}:`, error);
      const errorMessage = error instanceof Error ? error.message : '获取打印任务状态失败';
      return c.json({ success: false, message: errorMessage }, 500);
    }
  });

export default app;