"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.apiClientSendRoutes = apiClientSendRoutes;
const errors_1 = require("@yinuo-ngm/errors");
const hub_cookie_jar_1 = require("./hub-cookie-jar");
async function apiClientSendRoutes(fastify) {
    const api = fastify.api;
    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 && !body.requestId)
            throw new errors_1.GlobalError(errors_1.GlobalErrorCodes.BAD_REQUEST, "request or requestId is required");
        const useCookieJar = body.useCookieJar !== false;
        const sessionKey = body.sessionKey ?? `${scope}:${body.projectId ?? "global"}:${body.envId ?? "default"}`;
        if (body.clearCookieJar) {
            (0, hub_cookie_jar_1.clearCookieJar)(sessionKey);
        }
        const cookieFromJar = useCookieJar ? (0, hub_cookie_jar_1.getCookieJar)(sessionKey) : undefined;
        const nextRequest = await buildRequestWithCookie(api, {
            scope,
            projectId: body.projectId,
            requestId: body.requestId,
            request: body.request,
            cookie: cookieFromJar,
        });
        const result = await api.send({
            scope,
            projectId: body.projectId,
            requestId: nextRequest ? undefined : body.requestId,
            request: nextRequest ?? body.request,
            envId: body.envId,
            projectRoot: body.projectRoot,
        });
        if (useCookieJar) {
            const setCookies = extractSetCookieHeader(result?.response?.headers?.["set-cookie"]);
            if (setCookies.length > 0) {
                (0, hub_cookie_jar_1.mergeCookieJar)(sessionKey, setCookies);
            }
        }
        return result;
    });
}
async function buildRequestWithCookie(api, params) {
    if (!params.cookie)
        return params.request;
    const requestEntity = params.request
        ?? (params.requestId
            ? await api.getRequest(params.requestId, params.scope, params.projectId)
            : undefined);
    if (!requestEntity)
        return params.request;
    const next = {
        ...requestEntity,
        headers: Array.isArray(requestEntity.headers) ? [...requestEntity.headers] : [],
        auth: requestEntity.auth ? { ...requestEntity.auth } : undefined,
    };
    if (next.auth?.type === "cookie" && next.auth?.cookie?.value) {
        return next;
    }
    const cookieHeader = next.headers.find((h) => String(h?.key ?? "").toLowerCase() === "cookie");
    if (cookieHeader && cookieHeader.value) {
        return next;
    }
    if (cookieHeader) {
        cookieHeader.value = params.cookie;
        cookieHeader.enabled = true;
        return next;
    }
    next.headers.push({
        key: "cookie",
        value: params.cookie,
        enabled: true,
    });
    return next;
}
function extractSetCookieHeader(raw) {
    if (!raw)
        return [];
    return [raw];
}
