"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiClientEnvsRoutes = apiClientEnvsRoutes;
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 apiClientEnvsRoutes(fastify) {
    const env = fastify.api;
    fastify.get("/", async (req) => {
        const { scope, projectId } = parseScope(req.query);
        return await env.listEnvs(scope, projectId);
    });
    fastify.get("/:id", async (req, reply) => {
        const { scope, projectId } = parseScope(req.query);
        const id = req.params.id;
        const item = await env.getEnv(id, scope, projectId);
        if (!item) {
            reply.code(404);
            return { message: "env 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?.env?.id)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "env.id is required");
        await env.saveEnv(body.env, scope, body.projectId);
        return { id: body.env.id };
    });
    fastify.delete("/:id", async (req) => {
        const { scope, projectId } = parseScope(req.query);
        const id = req.params.id;
        await env.deleteEnv(id, scope, projectId);
        return { id };
    });
}
