"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiClientHistoryRoutes = apiClientHistoryRoutes;
const errors_1 = require("@yinuo-ngm/errors");
function parseScope(q) {
    const scope = (q?.scope ?? "project");
    const projectId = q?.projectId;
    if (scope === "project" && !projectId)
        throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "projectId is required when scope=project");
    return { scope, projectId };
}
function parseNum(v, fallback) {
    const n = Number(v);
    return Number.isFinite(n) ? n : fallback;
}
async function apiClientHistoryRoutes(fastify) {
    const api = fastify.api;
    fastify.get("/", async (req) => {
        const { scope, projectId } = parseScope(req.query);
        const limit = parseNum(req.query?.limit, 50);
        const offset = parseNum(req.query?.offset, 0);
        return await api.listHistory({ scope, projectId, limit, offset });
    });
    fastify.post("/purge", async (req) => {
        const body = req.body;
        const scope = body?.scope ?? "project";
        if (scope === "project" && !body.projectId)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "projectId is required when scope=project");
        const removed = await api.purgeHistory({
            scope,
            projectId: body.projectId,
            olderThan: body.olderThan,
            maxCount: body.maxCount,
        });
        return { removed };
    });
}
