"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiClientRequestsRoutes = apiClientRequestsRoutes;
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 };
}
async function apiClientRequestsRoutes(fastify) {
    const api = fastify.api;
    fastify.get("/", async (req) => {
        const { scope, projectId } = parseScope(req.query);
        const items = await api.listRequests(scope, projectId);
        return items;
    });
    fastify.get("/:id", async (req, reply) => {
        const { scope, projectId } = parseScope(req.query);
        const id = req.params.id;
        const item = await api.getRequest(id, scope, projectId);
        if (!item) {
            reply.code(404);
            return { message: "request not found", id };
        }
        return item;
    });
    fastify.post("/", 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");
        if (!body?.request?.id)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "request.id is required");
        await api.saveRequest(body.request, scope, body.projectId);
        return { id: body.request.id };
    });
    fastify.post("/update", 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");
        if (!body?.request?.id)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "request.id is required");
        const old = await api.getRequest(body.request.id, scope, body.projectId);
        if (!old)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.NOT_FOUND, "request not found: " + body.request.id);
        const updated = {
            ...old,
            ...body.request,
        };
        await api.saveRequest(updated, scope, body.projectId);
        return { id: body.request.id };
    });
    fastify.delete("/:id", async (req) => {
        const { scope, projectId } = parseScope(req.query);
        const id = req.params.id;
        await api.deleteRequest(id, scope, projectId);
        return { id };
    });
}
