import { Router } from 'express';
import { workService } from '../services/WorkService.js';
import { asyncHandler } from '../middleware/error.js';
import { authenticate } from '../middleware/auth.js';
import { taskQueueService } from '../services/TaskQueueService.js';

const router = Router();

// 所有路由需要认证
router.use(authenticate);

/**
 * 获取作品列表
 */
router.get(
  '/',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const { page, pageSize, accountId, platform, status, keyword } = req.query;

    const result = await workService.getWorks(userId, {
      page: page ? parseInt(page as string) : 1,
      pageSize: pageSize ? parseInt(pageSize as string) : 12,
      accountId: accountId ? parseInt(accountId as string) : undefined,
      platform: platform as string | undefined,
      status: status as string | undefined,
      keyword: keyword as string | undefined,
    });

    res.json({ success: true, data: result });
  })
);

/**
 * 获取作品统计
 */
router.get(
  '/stats',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const stats = await workService.getStats(userId);
    res.json({ success: true, data: stats });
  })
);

/**
 * 同步作品 - 使用任务队列
 */
router.post(
  '/sync',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const { accountId, accountName } = req.body;

    // 创建同步作品任务
    const task = taskQueueService.createTask(userId, {
      type: 'sync_works',
      title: accountName ? `同步作品 - ${accountName}` : '同步所有作品',
      accountId: accountId ? Number(accountId) : undefined,
    });

    res.json({ 
      success: true, 
      message: '作品同步任务已创建', 
      data: { 
        taskId: task.id, 
        status: 'pending' 
      } 
    });
  })
);

/**
 * 获取单个作品
 */
router.get(
  '/:id',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const workId = parseInt(req.params.id);
    const work = await workService.getWorkById(userId, workId);
    res.json({ success: true, data: work });
  })
);

/**
 * 删除平台上的作品
 */
router.post(
  '/:id/delete-platform',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const workId = parseInt(req.params.id);
    
    // 创建删除任务
    const task = taskQueueService.createTask(userId, {
      type: 'delete_work',
      title: '删除平台作品',
      data: { workId },
    });
    
    res.json({ 
      success: true, 
      message: '删除任务已创建',
      data: { taskId: task.id }
    });
  })
);

/**
 * 删除本地作品记录
 */
router.delete(
  '/:id',
  asyncHandler(async (req, res) => {
    const userId = req.user!.userId;
    const workId = parseInt(req.params.id);
    await workService.deleteWork(userId, workId);
    res.json({ success: true, message: '作品已删除' });
  })
);

export default router;
