"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertCatalogToLegacyFormat = convertCatalogToLegacyFormat;
exports.catalogToLegacy = catalogToLegacy;
const get_with_default_1 = require("../../objects/get-with-default");
const utils_1 = require("../../search/utils");
const util_1 = require("../../util");
const get_catalog_from_site_model_1 = require("../get-catalog-from-site-model");
/**
 * Converts the migrated catalog of a site model back into a legacy catalog format.
 * As the new catalog format is much more flexible than the legacy format, only supported
 * fields configurations (i.e., group ids) are transferred.
 *
 * @param modelToUpdate modified site model with a migrated catalog
 * @param currentModel currently persisted site model with a legacy catalog
 * @returns site model with any catalog group changes reflected in a legacy format
 */
function convertCatalogToLegacyFormat(modelToUpdate, currentModel) {
    const updatedModel = (0, util_1.cloneObject)(modelToUpdate);
    const catalog = (0, get_catalog_from_site_model_1.getCatalogFromSiteModel)(updatedModel);
    const legacyCatalog = catalogToLegacy(catalog);
    // If the catalog has groups array, we update the model with the legacy catalog
    if (Array.isArray(legacyCatalog.groups)) {
        updatedModel.data.catalog = legacyCatalog;
    }
    else {
        // This shouldn't happen, but in case something is malformed we protect the data integrity
        // by reverting to the catalog of the most recently fetched model
        updatedModel.data.catalog = (0, util_1.cloneObject)(currentModel.data.catalog);
        return updatedModel;
    }
    return updatedModel;
}
/**
 * Focused function converting an IHubCatalog to a legacy catalog format.
 * @param catalog
 * @returns
 */
function catalogToLegacy(catalog) {
    var _a;
    const legacyCatalog = {
        groups: [],
    };
    if ((_a = catalog.scopes) === null || _a === void 0 ? void 0 : _a.item) {
        const groupPredicate = (0, utils_1.getGroupPredicate)(catalog.scopes.item);
        if (groupPredicate) {
            // using getWithDefault to side-step test coverage for a condition
            // we can't replicate in a typed environment
            legacyCatalog.groups = (0, get_with_default_1.getWithDefault)(groupPredicate, "group.any", []);
        }
    }
    return legacyCatalog;
}
//# sourceMappingURL=convertCatalogToLegacyFormat.js.map