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

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

// 取消打印任务请求体Schema
const CancelPrintTaskBodySchema = z.object({
  reason: z.enum(['REFUND', 'MANUAL', 'TIMEOUT']).optional().default('MANUAL')
});

// 取消打印任务响应Schema
const CancelPrintTaskResponseSchema = 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']),
    cancelReason: z.string().nullable(),
    cancelledAt: z.string().nullable(),
    updatedAt: z.string()
  })
});

// 取消打印任务路由定义
const cancelPrintTaskRoute = createRoute({
  method: 'post',
  path: '/:taskId/cancel',
  middleware: [authMiddleware],
  request: {
    params: CancelPrintTaskParamsSchema,
    body: {
      content: {
        'application/json': { schema: CancelPrintTaskBodySchema }
      }
    }
  },
  responses: {
    200: {
      description: '打印任务取消成功',
      content: { 'application/json': { schema: CancelPrintTaskResponseSchema } }
    },
    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(cancelPrintTaskRoute, async (c) => {
    const user = c.get('user');
    const tenantId = user?.tenantId || 1;
    const { taskId } = c.req.valid('param');
    const { reason } = c.req.valid('json');

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

      // 将字符串转换为CancelReason枚举
      const cancelReason = reason as any as CancelReason;
      const task = await printTaskService.cancelPrintTask(tenantId, taskId, cancelReason);

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

      return c.json(validatedResponse, 200);
    } catch (error) {
      console.error(`[租户${tenantId}] 取消打印任务失败，任务ID: ${taskId}:`, error);
      const errorMessage = error instanceof Error ? error.message : '取消打印任务失败';

      // 根据错误类型返回不同的状态码
      if (errorMessage.includes('打印任务不存在')) {
        return c.json({ success: false, message: errorMessage }, 404);
      } else if (errorMessage.includes('无法取消')) {
        return c.json({ success: false, message: errorMessage }, 400);
      } else {
        return c.json({ success: false, message: errorMessage }, 500);
      }
    }
  });

export default app;