"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleDeleteRule = void 0;
const policy_1 = require("./policy");
const database_1 = require("./database");
async function hasDeletePermission(domain, databaseAdapter, context, options) {
    const allowed = await (0, policy_1.ruleHasPermission)(`delete.${domain}`, context, databaseAdapter, options);
    if (allowed !== true)
        throw { message: 'You have insufficient permission to this resource' };
}
async function handleDeleteOneRule(domain, ruleData, ruleResponse, databaseAdapter, context, options) {
    const filter = {};
    delete ruleData.filter;
    filter._id = ruleData.id;
    ruleData.filter = filter;
    const wOptions = { bypassDomainVerification: context && context.useMasterKey === true, transaction: null };
    ruleResponse[`delete${domain}`] =
        await (0, database_1.removeDataInStore)(domain, ruleData, context, databaseAdapter, wOptions, options);
    return ruleResponse;
}
async function handleDeleteManyRule(domain, ruleData, ruleResponse, databaseAdapter, context, options) {
    if (!ruleData.filter)
        throw new Error('filter field is required if you dont supply id field');
    if (ruleData?.filter && Array.isArray(ruleData?.filter) && ruleData.filter.length === 0)
        throw new Error('Empty filter array is not supported in delete rule');
    if (ruleData?.filter && Object.keys(ruleData?.filter).length === 0)
        throw new Error('Empty filter map is not supported in delete rule');
    const wOptions = { bypassDomainVerification: context && context.useMasterKey === true, transaction: null };
    ruleResponse[`delete${domain}`] =
        await (0, database_1.removeDataInStore)(domain, ruleData, context, databaseAdapter, wOptions, options);
    return ruleResponse;
}
async function handleDeleteRule(domain, ruleData, ruleResponse, databaseAdapter, context, options) {
    await hasDeletePermission(domain, databaseAdapter, context, options);
    if (ruleData.id)
        return handleDeleteOneRule(domain, ruleData, ruleResponse, databaseAdapter, context, options);
    else
        return handleDeleteManyRule(domain, ruleData, ruleResponse, databaseAdapter, context, options);
}
exports.handleDeleteRule = handleDeleteRule;
