"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getRoutingErrorMessage = exports.getCliproxyRoutingTarget = exports.fetchCliproxyRoutingResponse = exports.getCliproxyRoutingManagementUrl = void 0;
const https = __importStar(require("https"));
const proxy_target_resolver_1 = require("../proxy/proxy-target-resolver");
const ROUTING_TIMEOUT_MS = 5000;
const CLIPROXY_ROUTING_MANAGEMENT_PATH = '/v0/management/routing/strategy';
function getCliproxyRoutingManagementUrl(target) {
    return (0, proxy_target_resolver_1.buildProxyUrl)(target, CLIPROXY_ROUTING_MANAGEMENT_PATH);
}
exports.getCliproxyRoutingManagementUrl = getCliproxyRoutingManagementUrl;
async function fetchCliproxyRoutingResponse(target, method, body) {
    const url = getCliproxyRoutingManagementUrl(target);
    const headers = (0, proxy_target_resolver_1.buildManagementHeaders)(target, body ? { 'Content-Type': 'application/json' } : {});
    if (target.protocol !== 'https' || !target.allowSelfSigned) {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), ROUTING_TIMEOUT_MS);
        try {
            return await fetch(url, {
                method,
                headers,
                body: body ? JSON.stringify(body) : undefined,
                signal: controller.signal,
            });
        }
        finally {
            clearTimeout(timeoutId);
        }
    }
    return new Promise((resolve, reject) => {
        const agent = new https.Agent({ rejectUnauthorized: false });
        let settled = false;
        const settle = (callback) => {
            if (settled)
                return;
            settled = true;
            clearTimeout(timeoutId);
            callback();
        };
        const timeoutId = setTimeout(() => {
            const error = new Error('Request timeout');
            req.destroy(error);
            settle(() => reject(error));
        }, ROUTING_TIMEOUT_MS);
        const req = https.request(url, {
            method,
            headers,
            agent,
            timeout: ROUTING_TIMEOUT_MS,
        }, (res) => {
            let payload = '';
            res.setEncoding('utf8');
            res.on('data', (chunk) => {
                payload += chunk;
            });
            res.on('end', () => {
                settle(() => resolve(new Response(payload, {
                    status: res.statusCode || 500,
                    statusText: res.statusMessage ?? '',
                    headers: typeof res.headers['content-type'] === 'string'
                        ? { 'Content-Type': res.headers['content-type'] }
                        : undefined,
                })));
            });
        });
        req.on('error', (error) => {
            settle(() => reject(error));
        });
        req.on('timeout', () => {
            const error = new Error('Request timeout');
            req.destroy(error);
            settle(() => reject(error));
        });
        if (body) {
            req.write(JSON.stringify(body));
        }
        req.end();
    });
}
exports.fetchCliproxyRoutingResponse = fetchCliproxyRoutingResponse;
function getCliproxyRoutingTarget() {
    return (0, proxy_target_resolver_1.getProxyTarget)();
}
exports.getCliproxyRoutingTarget = getCliproxyRoutingTarget;
function getRoutingErrorMessage(response, fallback) {
    return response
        .json()
        .then((data) => {
        if (data && typeof data === 'object' && 'error' in data && typeof data.error === 'string') {
            return data.error;
        }
        return fallback;
    })
        .catch(() => fallback);
}
exports.getRoutingErrorMessage = getRoutingErrorMessage;
//# sourceMappingURL=routing-strategy-http.js.map