"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertFeaturesToLegacyCapabilities = void 0;
const get_prop_1 = require("../../../objects/get-prop");
const capabilityToFeatureMap_1 = require("./capabilityToFeatureMap");
const set_prop_1 = require("../../../objects/set-prop");
/**
 * Site capabilities are currently saved as an array on the
 * site.data.values.capabilities. We want to migragte these
 * legacy capabilities over to features in the new permissions
 * system; however, we must continue persisting updates to
 * these features in the legacy capabilities array until the
 * existing site capabilities in our application are plumbed
 * to work off of permissions
 *
 * This function is called within updateSite to ensure
 * the legacy capabilities array is kept up-to-date
 *
 * TODO: Remove once site capabilities use permissions
 *
 * @param modelToUpdate
 * @param currentModel
 */
const convertFeaturesToLegacyCapabilities = (modelToUpdate, currentModel) => {
    let legacyCapabilityFeatureFlags = {};
    // 1. convert legacy capabilities to a feature flag hash
    ((0, get_prop_1.getProp)(currentModel, "data.values.capabilities") || []).forEach((capability) => {
        legacyCapabilityFeatureFlags[capability] = true;
    });
    // 2. override legacy capabilities that are driven by features
    const features = (0, get_prop_1.getProp)(modelToUpdate, "data.settings.features") || {};
    legacyCapabilityFeatureFlags = capabilityToFeatureMap_1.capabilityToFeatureMap.reduce((capabilities, map) => {
        // TODO: remove istanbul exception once we include a
        // legacy capability that satisfies the second condition
        const featureFlag = map.negate
            ? !features[map.feature]
            : /* istanbul ignore next */ features[map.feature];
        return Object.assign(Object.assign({}, capabilities), { [map.capability]: featureFlag });
    }, legacyCapabilityFeatureFlags);
    // 3. convert legacy capabilities back to an array and persist on model
    const updatedCapabilities = Object.entries(legacyCapabilityFeatureFlags).reduce((acc, [key, value]) => {
        // if you are updating this file, remove this comment and address the lint error
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        value && acc.push(key);
        return acc;
    }, []);
    (0, set_prop_1.setProp)("data.values.capabilities", updatedCapabilities, modelToUpdate);
    return modelToUpdate;
};
exports.convertFeaturesToLegacyCapabilities = convertFeaturesToLegacyCapabilities;
//# sourceMappingURL=convertFeaturesToLegacyCapabilities.js.map