"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleUpdateRule = void 0;
const database_1 = require("./database");
const policy_1 = require("./policy");
async function checkUpdatePermission(domain, databaseAdapter, context, options) {
    const allowed = await (0, policy_1.ruleHasPermission)(`update.${domain}`, context, databaseAdapter, options);
    if (allowed !== true)
        throw { message: 'You have insufficient permission to this resource' };
}
function sanitizeUpdateModel(data) {
    if (!data?.update) {
        throw { message: 'Please update field is required, which contains properties to update a document' };
    }
    if (!data.hasOwnProperty('id') && !data.hasOwnProperty('filter')) {
        throw { message: 'Bad data format in update rule, no filter nor id' };
    }
    if (data?.id) {
        const filter = {};
        delete data.filter;
        filter._id = data.id;
        data.filter = filter;
    }
    if (data?.filter && Object.keys(data?.filter).length === 0) {
        throw { message: 'Empty map is not supported in update rule' };
    }
    return data;
}
async function updateSingleDoc(context, databaseAdapter, domain, data, options) {
    data = sanitizeUpdateModel(data);
    const uO = { bypassDomainVerification: context?.useMasterKey === true, transaction: null };
    return (0, database_1.updateDataInStore)(domain, data, context, databaseAdapter, uO, options);
}
async function updateManyDoc(context, databaseAdapter, domain, ruleData, options) {
    ruleData = ruleData.map(z => sanitizeUpdateModel(z));
    const uO = { bypassDomainVerification: context?.useMasterKey === true, transaction: null };
    return (0, database_1.updateManyData)(domain, ruleData, context, databaseAdapter, uO, options);
}
async function handleUpdateRule(domain, ruleData, ruleResponse, databaseAdapter, context, options) {
    await checkUpdatePermission(domain, databaseAdapter, context, options);
    if (ruleData && Array.isArray(ruleData)) {
        ruleResponse[`update${domain}`]
            = await updateManyDoc(context, databaseAdapter, domain, ruleData, options);
    }
    else {
        ruleResponse[`update${domain}`]
            = await updateSingleDoc(context, databaseAdapter, domain, ruleData, options);
    }
    return ruleResponse;
}
exports.handleUpdateRule = handleUpdateRule;
