"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeRequest = makeRequest;
exports.getProviderFromCloud = getProviderFromCloud;
exports.getConfigFromCloud = getConfigFromCloud;
exports.isCloudProvider = isCloudProvider;
exports.getCloudDatabaseId = getCloudDatabaseId;
exports.getPluginSeverityOverridesFromCloud = getPluginSeverityOverridesFromCloud;
const constants_1 = require("../constants");
const fetch_1 = require("../fetch");
const cloud_1 = require("../globalConfig/cloud");
const logger_1 = __importDefault(require("../logger"));
const providers_1 = require("../validators/providers");
const invariant_1 = __importDefault(require("./invariant"));
function makeRequest(path, method, body) {
    const apiHost = cloud_1.cloudConfig.getApiHost();
    const apiKey = cloud_1.cloudConfig.getApiKey();
    const url = `${apiHost}/api/v1/${path.startsWith('/') ? path.slice(1) : path}`;
    try {
        return (0, fetch_1.fetchWithProxy)(url, {
            method,
            body: JSON.stringify(body),
            headers: { Authorization: `Bearer ${apiKey}` },
        });
    }
    catch (e) {
        logger_1.default.error(`[Cloud] Failed to make request to ${url}: ${e}`);
        if (e.cause) {
            logger_1.default.error(`Cause: ${e.cause}`);
        }
        throw e;
    }
}
async function getProviderFromCloud(id) {
    if (!cloud_1.cloudConfig.isEnabled()) {
        throw new Error(`Could not fetch Provider ${id} from cloud. Cloud config is not enabled. Please run \`trusys auth login\` to login.`);
    }
    try {
        const response = await makeRequest(`providers/${id}`, 'GET');
        if (!response.ok) {
            const errorMessage = await response.text();
            logger_1.default.error(`[Cloud] Failed to fetch provider from cloud: ${errorMessage}. HTTP Status: ${response.status} -- ${response.statusText}.`);
            throw new Error(`Failed to fetch provider from cloud: ${response.statusText}`);
        }
        const body = await response.json();
        logger_1.default.debug(`Provider fetched from cloud: ${id}`);
        logger_1.default.debug(`Provider from cloud: ${JSON.stringify(body, null, 2)}`);
        const provider = providers_1.ProviderOptionsSchema.parse(body.config);
        // The provider options schema has ID field as optional but we know it's required for cloud providers
        (0, invariant_1.default)(provider.id, `Provider ${id} has no id in ${body.config}`);
        return { ...provider, id: provider.id };
    }
    catch (e) {
        logger_1.default.error(`Failed to fetch provider from cloud: ${id}.`);
        logger_1.default.error(String(e));
        throw new Error(`Failed to fetch provider from cloud: ${id}.`);
    }
}
async function getConfigFromCloud(id, providerId) {
    if (!cloud_1.cloudConfig.isEnabled()) {
        throw new Error(`Could not fetch Config ${id} from cloud. Cloud config is not enabled. Please run \`trusys auth login\` to login.`);
    }
    try {
        const response = await makeRequest(`redteam/configs/${id}/unified${providerId ? `?providerId=${providerId}` : ''}`, 'GET');
        if (!response.ok) {
            const errorMessage = await response.text();
            logger_1.default.error(`[Cloud] Failed to fetch config from cloud: ${errorMessage}. HTTP Status: ${response.status} -- ${response.statusText}.`);
            throw new Error(`Failed to fetch config from cloud: ${response.statusText}`);
        }
        const body = await response.json();
        logger_1.default.info(`Config fetched from cloud: ${id}`);
        logger_1.default.debug(`Config from cloud: ${JSON.stringify(body, null, 2)}`);
        return body;
    }
    catch (e) {
        logger_1.default.error(`Failed to fetch config from cloud: ${id}.`);
        logger_1.default.error(String(e));
        throw new Error(`Failed to fetch config from cloud: ${id}.`);
    }
}
function isCloudProvider(providerPath) {
    return providerPath.startsWith(constants_1.CLOUD_PROVIDER_PREFIX);
}
function getCloudDatabaseId(providerPath) {
    if (!isCloudProvider(providerPath)) {
        throw new Error(`Provider path ${providerPath} is not a cloud provider.`);
    }
    return providerPath.slice(constants_1.CLOUD_PROVIDER_PREFIX.length);
}
/**
 * Get the plugin severity overrides for a cloud provider.
 * @param cloudProviderId - The cloud provider ID.
 * @returns The plugin severity overrides.
 */
async function getPluginSeverityOverridesFromCloud(cloudProviderId) {
    if (!cloud_1.cloudConfig.isEnabled()) {
        throw new Error(`Could not fetch plugin severity overrides from cloud. Cloud config is not enabled. Please run \`trusys auth login\` to login.`);
    }
    try {
        const response = await makeRequest(`/providers/${cloudProviderId}`, 'GET');
        if (!response.ok) {
            const errorMessage = await response.text();
            const formattedErrorMessage = `Failed to provider from cloud: ${errorMessage}. HTTP Status: ${response.status} -- ${response.statusText}.`;
            logger_1.default.error(`[Cloud] ${formattedErrorMessage}`);
            throw new Error(formattedErrorMessage);
        }
        const body = await response.json();
        if (body.pluginSeveritySetId) {
            // Fetch the plugin severity set from the cloud:
            const pluginSeveritySetResponse = await makeRequest(`/redteam/plugins/severity-sets/${body.pluginSeveritySetId}`, 'GET');
            if (!pluginSeveritySetResponse.ok) {
                const errorMessage = await pluginSeveritySetResponse.text();
                const formattedErrorMessage = `Failed to fetch plugin severity set from cloud: ${errorMessage}. HTTP Status: ${pluginSeveritySetResponse.status} -- ${pluginSeveritySetResponse.statusText}.`;
                logger_1.default.error(`[Cloud] ${formattedErrorMessage}`);
                throw new Error(formattedErrorMessage);
            }
            const pluginSeveritySet = await pluginSeveritySetResponse.json();
            logger_1.default.debug(`Plugin severity overrides ${pluginSeveritySet.id} fetched from cloud: ${JSON.stringify(pluginSeveritySet.members, null, 2)}`);
            return {
                id: pluginSeveritySet.id,
                severities: pluginSeveritySet.members.reduce((acc, member) => ({
                    ...acc,
                    [member.pluginId]: member.severity,
                }), {}),
            };
        }
        else {
            logger_1.default.debug(`No plugin severity overrides found for cloud provider ${cloudProviderId}`);
            return null;
        }
    }
    catch (e) {
        logger_1.default.error(`Failed to fetch plugin severity overrides from cloud.`);
        logger_1.default.error(String(e));
        throw new Error(`Failed to fetch plugin severity overrides from cloud.`);
    }
}
//# sourceMappingURL=cloud.js.map