"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const router_1 = __importDefault(require("@koa/router"));
const queue_service_1 = require("./queue.service");
const errorHandler_1 = require("../../middleware/errorHandler");
const auth_1 = require("../../middleware/auth");

const router = new router_1.default();

// 获取队列状态
router.get('/status', async (ctx) => {
    const status = await queue_service_1.queueService.getStatus();
    ctx.body = { code: 0, message: 'success', data: status };
});

// 获取任务列表
router.get('/tasks', async (ctx) => {
    const { status, page = '1', pageSize = '20' } = ctx.query;
    const result = await queue_service_1.queueService.getTasks(
        status || null,
        parseInt(page, 10),
        parseInt(pageSize, 10)
    );
    ctx.body = { code: 0, message: 'success', data: result };
});

// 添加任务
router.post('/task', auth_1.optionalAuth, async (ctx) => {
    const userId = ctx.state.user?.userId;
    const { text, voiceId, voiceParams } = ctx.request.body;

    try {
        const result = await queue_service_1.queueService.addTask(userId, text, voiceId, voiceParams);
        ctx.body = { code: 0, message: '任务已加入队列', data: result };
    } catch (err) {
        if (err.message.includes('请输入') || err.message.includes('请选择') || err.message.includes('已有')) {
            throw new errorHandler_1.BadRequestError(err.message);
        }
        throw err;
    }
});

// 删除任务
router.delete('/task/:audioId', async (ctx) => {
    const { audioId } = ctx.params;
    try {
        const result = await queue_service_1.queueService.deleteTask(audioId);
        ctx.body = { code: 0, message: '任务已删除', data: result };
    } catch (err) {
        if (err.message === '任务不存在') {
            throw new errorHandler_1.NotFoundError(err.message);
        }
        if (err.message === '任务正在处理中，无法删除') {
            throw new errorHandler_1.BadRequestError(err.message);
        }
        throw err;
    }
});

// 启动队列
router.post('/start', async (ctx) => {
    const result = queue_service_1.queueService.start();
    ctx.body = { code: 0, message: result.message, data: result };
});

// 停止队列
router.post('/stop', async (ctx) => {
    const result = queue_service_1.queueService.stop();
    ctx.body = { code: 0, message: result.message, data: result };
});

// 清空待处理任务
router.delete('/tasks', async (ctx) => {
    const result = await queue_service_1.queueService.clearPendingTasks();
    ctx.body = { code: 0, message: '已清空待处理任务', data: result };
});

exports.default = router;