"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchBlobFileFromAzure = void 0;
exports.urlAlreadyHasAzureSasSignature = urlAlreadyHasAzureSasSignature;
exports.extractBlobUrlFromFetchResponse = extractBlobUrlFromFetchResponse;
exports.resolvePrivateBlobDownloadUrl = resolvePrivateBlobDownloadUrl;
const callControlPlaneApi_1 = require("../callContolPlane/callControlPlaneApi");
/** Azure Blob SAS URLs include a `sig` query param; CP fetch-private-file is unnecessary. */
function urlAlreadyHasAzureSasSignature(raw) {
    const s = raw.trim();
    if (!/^https?:\/\//i.test(s)) {
        return false;
    }
    try {
        return new URL(s).searchParams.has('sig');
    }
    catch {
        return /[?&]sig=/i.test(s);
    }
}
/** Extract a download URL from CP `/fetch-private-file` response payload. */
function extractBlobUrlFromFetchResponse(response) {
    if (typeof response === 'string') {
        const trimmed = response.trim();
        return trimmed.length > 0 ? trimmed : undefined;
    }
    if (response && typeof response === 'object') {
        const record = response;
        const direct = record.url ?? record.blobUrl ?? record.uri ?? record.downloadUrl ?? record.signedUrl;
        if (typeof direct === 'string' && direct.trim().length > 0) {
            return direct.trim();
        }
        const nested = record.response ?? record.data;
        if (nested !== undefined && nested !== response) {
            return extractBlobUrlFromFetchResponse(nested);
        }
        const firstHttp = Object.values(record).find((v) => typeof v === 'string' && /^https?:\/\//i.test(v.trim()));
        if (typeof firstHttp === 'string') {
            return firstHttp.trim();
        }
    }
    return undefined;
}
const fetchBlobFileFromAzure = async (blobUrl, token, apiKey, expiryInHours) => {
    const data = await (0, callControlPlaneApi_1.callControlPlane)(`/fetch-private-file`, {
        method: 'GET',
        params: {
            blobUrl,
            expiryInHours,
            ...(apiKey && { trusysApiKey: apiKey }),
        },
    }, (0, callControlPlaneApi_1.formatControlPlaneAuthorization)(token, apiKey));
    if (data?.error) {
        throw new Error(typeof data.error === 'string' ? data.error : 'Failed to fetch private file URL');
    }
    return data?.response;
};
exports.fetchBlobFileFromAzure = fetchBlobFileFromAzure;
/**
 * Resolve a blob storage path to an HTTPS URL suitable for download.
 * Skips CP when the stored URL already includes a SAS signature.
 */
async function resolvePrivateBlobDownloadUrl(blobUrl, token, apiKey, expiryInHours) {
    const trimmed = blobUrl?.trim();
    if (!trimmed) {
        throw new Error('Bundle blob URL is missing');
    }
    if (urlAlreadyHasAzureSasSignature(trimmed)) {
        return trimmed;
    }
    const resolved = await (0, exports.fetchBlobFileFromAzure)(trimmed, token, apiKey, expiryInHours);
    const downloadUrl = extractBlobUrlFromFetchResponse(resolved);
    if (!downloadUrl) {
        throw new Error('Failed to resolve bundle download URL from blob storage');
    }
    return downloadUrl;
}
//# sourceMappingURL=index.js.map