"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleDomainChanges = handleDomainChanges;
const get_prop_1 = require("../../objects/get-prop");
const add_domain_1 = require("../domains/add-domain");
const removeDomainByHostname_1 = require("../domains/removeDomainByHostname");
/**
 * Given two site models, determine the domain changes and apply them
 * @param currentModel
 * @param updatedModel
 * @param requestOptions
 * @private
 */
async function handleDomainChanges(updatedModel, currentModel, requestOptions) {
    const defaultDomainRecord = {
        clientKey: updatedModel.data.values.clientId,
        orgId: requestOptions.portalSelf.id,
        orgTitle: requestOptions.portalSelf.name,
        orgKey: requestOptions.portalSelf.urlKey,
        siteId: updatedModel.item.id,
        siteTitle: updatedModel.item.title,
        sslOnly: true,
    };
    const domainChanges = {
        remove: [],
        add: [],
    };
    ["customHostname", "defaultHostname"].forEach((key) => {
        const currentValue = (0, get_prop_1.getProp)(currentModel, `data.values.${key}`) || "";
        const updatedValue = (0, get_prop_1.getProp)(updatedModel, `data.values.${key}`) || "";
        if (updatedValue.toLowerCase() !== currentValue.toLowerCase()) {
            domainChanges.remove.push(currentValue);
            domainChanges.add.push(updatedValue);
        }
    });
    const domainChangePromises = [];
    // handle additions
    domainChanges.add.map((hostname) => {
        const domainOpts = Object.assign({ hostname }, defaultDomainRecord);
        domainChangePromises.push((0, add_domain_1.addDomain)(domainOpts, requestOptions));
    });
    // handle removals
    domainChanges.remove.map((hostname) => {
        domainChangePromises.push((0, removeDomainByHostname_1.removeDomainByHostname)(hostname, requestOptions));
    });
    return Promise.all(domainChangePromises);
    // TODO: Error handling & OperationStack
}
//# sourceMappingURL=handleDomainChanges.js.map