import { Router } from 'express';
import { asyncHandler } from '../middleware/error.js';
import { taskQueueService } from '../services/TaskQueueService.js';
import type { CreateTaskRequest } from '@media-manager/shared';

const router = Router();

/**
 * 获取当前用户的任务列表
 */
router.get(
  '/',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const tasks = taskQueueService.getUserTasks(userId);
    res.json({
      success: true,
      data: { tasks },
    });
  })
);

/**
 * 获取活跃任务
 */
router.get(
  '/active',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const tasks = taskQueueService.getActiveTasks(userId);
    res.json({
      success: true,
      data: { tasks },
    });
  })
);

/**
 * 创建新任务
 */
router.post(
  '/',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const request = req.body as CreateTaskRequest;
    
    const task = taskQueueService.createTask(userId, request);
    
    res.json({
      success: true,
      message: '任务已创建',
      data: { task },
    });
  })
);

/**
 * 取消任务
 */
router.post(
  '/:taskId/cancel',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const { taskId } = req.params;
    
    const success = taskQueueService.cancelTask(userId, taskId);
    
    if (success) {
      res.json({
        success: true,
        message: '任务已取消',
      });
    } else {
      res.status(400).json({
        success: false,
        message: '无法取消任务',
      });
    }
  })
);

export default router;
