"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = taskRoutes;
const errors_1 = require("@yinuo-ngm/errors");
async function ensureSpecs(fastify, projectId) {
    const specs = await fastify.core.task.listSpecsByProject(projectId);
    if (specs.length === 0) {
        await fastify.core.task.refreshByProject(projectId);
    }
}
async function taskRoutes(fastify) {
    fastify.get("/list/:projectId", async (req) => {
        const { projectId } = req.params;
        await ensureSpecs(fastify, projectId);
        return fastify.core.task.listViewsByProject(projectId);
    });
    fastify.post("/refresh/:projectId", async (req) => {
        const { projectId } = req.params;
        return await fastify.core.task.refreshByProject(projectId);
    });
    fastify.post("/start", async (req) => {
        const body = req.body;
        const taskId = body?.taskId?.trim();
        if (!taskId)
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.TASK_ID_REQUIRED, "taskId is required", { body });
        return await fastify.core.task.start(taskId);
    });
    fastify.post("/stop", async (req) => {
        const body = req.body;
        const taskId = body?.taskId?.trim();
        if (!taskId)
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.TASK_ID_REQUIRED, "taskId is required", { body });
        return await fastify.core.task.stop(taskId);
    });
    fastify.post("/restart", async (req) => {
        const body = req.body;
        const taskId = body?.taskId?.trim();
        if (!taskId)
            throw new errors_1.CoreError(errors_1.CoreErrorCodes.TASK_ID_REQUIRED, "taskId is required", { body });
        return await fastify.core.task.restart(taskId);
    });
    fastify.get("/status/:taskId", async (req) => {
        const { taskId } = req.params;
        return await fastify.core.task.status(taskId);
    });
    fastify.get("/active", async () => {
        return await fastify.core.task.listActive();
    });
    fastify.get("/log/run/:runId", async (req) => {
        const { runId } = req.params;
        const { tail } = req.query;
        const limit = Math.min(Math.max(Number(tail) || 200, 1), 5000);
        return await fastify.core.task.getTailLogsByRun(runId, limit);
    });
}
