"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.callControlPlaneWithFormData = exports.callControlPlane = void 0;
exports.formatControlPlaneAuthorization = formatControlPlaneAuthorization;
const logger_1 = require("../../logger");
/** Control Plane expects `Authorization: Bearer <token>` (same as dataset/media uploads). */
function formatControlPlaneAuthorization(token, apiKey) {
    const raw = Array.isArray(token) ? token[0] : token;
    const trimmed = String(raw ?? '').trim();
    if (!trimmed) {
        if (typeof apiKey === 'string' && apiKey.trim().length > 0) {
            return '';
        }
        throw new Error('Authentication token or API key is required');
    }
    return /^Bearer\s+/i.test(trimmed) ? trimmed : `Bearer ${trimmed}`;
}
const callControlPlane = async (endpoint, options = {}, token, controlPlaneUrl) => {
    {
        /*if (!token || token.trim() === '') {
        throw new Error('Authentication token is required');
      }*/
    }
    const { method = 'GET', params, headers = {}, retryCount = 0 } = options;
    const urlBase = controlPlaneUrl ?? process.env.CP_API_BASE_URL;
    let url = `${urlBase}/api/v/1${endpoint}`;
    const fetchOptions = {
        method,
        headers: {
            'Content-Type': 'application/json',
            ...(token ? { Authorization: token } : {}),
            ...headers,
        },
    };
    // Handle params based on method
    if (method === 'GET' && params) {
        const queryString = new URLSearchParams(params).toString();
        url += `?${queryString}`;
    }
    else if (params) {
        fetchOptions.body = JSON.stringify(params);
    }
    // logger.info(`URL: ${url}`);  
    logger_1.logger.info(` Control Plane API URL: ${url}`);
    logger_1.logger.info(` Control Plane API Fetch Options: ${JSON.stringify(fetchOptions)}`);
    try {
        const response = await fetch(url, fetchOptions);
        const data = await response.json();
        if (!response.ok) {
            // Retry on 500 errors if retryCount > 0
            if (retryCount > 0 && response.status >= 500 && response.status < 600) {
                logger_1.logger.warn(`Retrying request due to ${response.status} error. Retries remaining: ${retryCount}`);
                return (0, exports.callControlPlane)(endpoint, { ...options, retryCount: retryCount - 1 }, token, controlPlaneUrl);
            }
            logger_1.logger.error(data?.message);
            return { error: data?.message || 'An error occurred', status: response.status };
        }
        return data;
    }
    catch (error) {
        logger_1.logger.error(error);
        return { error: error.message || 'Network error' };
    }
};
exports.callControlPlane = callControlPlane;
const callControlPlaneWithFormData = async (endpoint, formData, options = {}, token, controlPlaneUrl) => {
    const authHeader = formatControlPlaneAuthorization(token);
    const { method = 'POST', headers = {} } = options;
    const urlBase = controlPlaneUrl ?? process.env.CP_API_BASE_URL;
    const url = `${urlBase}/api/v/1${endpoint}`;
    const fetchOptions = {
        method,
        headers: {
            Authorization: authHeader,
            ...headers,
        },
        body: formData,
    };
    try {
        const response = await fetch(url, fetchOptions);
        const data = await response.json();
        if (!response.ok) {
            return { error: data?.message || 'An error occurred', status: response.status };
        }
        return data;
    }
    catch (error) {
        return { error: error.message || 'Network error' };
    }
};
exports.callControlPlaneWithFormData = callControlPlaneWithFormData;
//# sourceMappingURL=callControlPlaneApi.js.map