import { getEndpoint, NOTIFICATIONS, ACCOUNTS, } from "./endpoints.const";
import { JWTUtils } from "./jwt.utils";
export const request = async (payload) => {
    const headers = {};
    if (payload.camundaAuth) {
        if (JWTUtils.isExpired(payload.camundaAuth.token) &&
            payload.camundaAuth.refreshTokenMethod) {
            const newToken = await payload.camundaAuth?.refreshTokenMethod?.();
            headers.Authorization = `Bearer ${newToken}`;
        }
        else {
            headers.Authorization = `Bearer ${payload.camundaAuth.token}`;
        }
    }
    const type = payload.type ?? "json";
    if (type) {
        switch (type) {
            case "json":
                headers["Content-Type"] = "application/json";
                break;
            case "text":
                headers["Content-Type"] = "text/plain";
                break;
        }
    }
    const body = payload.body && type === "json"
        ? JSON.stringify(payload.body)
        : payload.body instanceof FormData
            ? payload.body
            : undefined;
    let base;
    if (payload.base) {
        switch (payload.base) {
            case "notifications":
                if (payload.endpoints?.notifications) {
                    base = payload.endpoints.notifications;
                }
                else if (payload.stage) {
                    base = getEndpoint(payload.stage, NOTIFICATIONS);
                }
                break;
            case "accounts":
                if (payload.endpoints?.accounts) {
                    base = payload.endpoints.accounts;
                }
                else if (payload.stage) {
                    base = getEndpoint(payload.stage, ACCOUNTS);
                }
        }
    }
    const url = base ? `${base}/${payload.url}` : payload.url;
    try {
        const response = await fetch(url, {
            method: payload.method ? payload.method.toUpperCase() : "GET",
            headers,
            body,
        });
        if (response.status >= 400) {
            if (payload.enableLogs)
                console.error(response.statusText, response.status);
            return {
                success: false,
                status: response.status,
                error: response.statusText,
            };
        }
        const responseType = payload.responseType ?? type;
        let res;
        switch (responseType) {
            case "json":
                res = await response.json();
                break;
            case "text":
                res = await response.text();
                break;
            default:
                res = response;
        }
        return { success: true, result: res };
    }
    catch (error) {
        if (payload.enableLogs)
            console.error("API request failed:", error);
        return { success: false, error: error?.toString() };
    }
};
