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

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

// 重试打印任务响应Schema
const RetryPrintTaskResponseSchema = z.object({
  success: z.boolean(),
  data: z.object({
    id: z.number(),
    tenantId: z.number(),
    taskId: z.string(),
    printStatus: z.enum(['PENDING', 'DELAYED', 'PRINTING', 'SUCCESS', 'FAILED', 'CANCELLED']),
    retryCount: z.number(),
    errorMessage: z.string().nullable(),
    updatedAt: z.string()
  })
});

// 重试打印任务路由定义
const retryPrintTaskRoute = createRoute({
  method: 'post',
  path: '/:taskId/retry',
  middleware: [authMiddleware],
  request: {
    params: RetryPrintTaskParamsSchema
  },
  responses: {
    200: {
      description: '打印任务重试成功',
      content: { 'application/json': { schema: RetryPrintTaskResponseSchema } }
    },
    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(retryPrintTaskRoute, 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 task = await printTaskService.retryPrintTask(tenantId, taskId);

      // 验证响应格式
      const response = {
        success: true as const,
        data: {
          id: task.id,
          tenantId: task.tenantId,
          taskId: task.taskId,
          printStatus: task.printStatus,
          retryCount: task.retryCount,
          errorMessage: task.errorMessage,
          updatedAt: task.updatedAt.toISOString()
        }
      };
      const validatedResponse = await parseWithAwait(RetryPrintTaskResponseSchema, response);

      return c.json(validatedResponse, 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;