"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertVariablesSummaryToPostmanFormat = convertVariablesSummaryToPostmanFormat;
exports.exportVariables = exportVariables;
exports.sanitizeExportedVariables = sanitizeExportedVariables;
const VariableUtils_1 = require("./VariableUtils");
const variable_constants_1 = require("./variable-constants");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
function convertVariablesSummaryToPostmanFormat(summary) {
    const effectiveVariables = { ...summary.effective };
    const values = Object.keys(effectiveVariables).map((key) => ({
        key,
        value: effectiveVariables[key],
    }));
    return {
        values,
    };
}
function exportVariables(postmanResult) {
    const variablePrecedence = [
        postmanResult?.globals.values,
        postmanResult?.collection.variables,
        postmanResult?.environment.values,
    ].filter((variables) => !!variables);
    const exportedVariables = {};
    variablePrecedence
        .flatMap((variableList) => variableList.all())
        .filter((variable) => Boolean(variable.key) && !variable.key?.startsWith(variable_constants_1.FLOW_NAMESPACE))
        .forEach((variable) => (exportedVariables[variable.key] = variable.value));
    return exportedVariables;
}
function sanitizeExportedVariables(variables) {
    const normalized = {};
    if (variables) {
        return normalizeExportedVariables(filterExportedVariables(variables));
    }
    return normalized;
}
function normalizeExportedVariables(variables) {
    const normalized = {};
    Object.keys(variables).forEach((name) => {
        normalized[(0, VariableUtils_1.addUserNamespace)(name)] = variables[name];
    });
    return normalized;
}
function filterExportedVariables(variables) {
    const filtered = {};
    Object.keys(variables)
        .filter((name) => (0, mablscriptFind_1.isValidUserVariableName)(name))
        .forEach((name) => {
        filtered[name] = variables[name];
    });
    return filtered;
}
