"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.policyRule = void 0;
const policy_1 = require("./policy");
function sanitizeRuleResponse(ruleResponse) {
    if (!ruleResponse.policy) {
        ruleResponse.policy = {};
    }
    return ruleResponse;
}
async function policyAdd(data, ruleResponse, databaseAdapter, context, options) {
    const authorizationResults = {};
    for (const rule of Object.keys(data)) {
        authorizationResults[rule] = await (0, policy_1.addPolicyRule)(rule, data[rule], databaseAdapter, context, options);
    }
    ruleResponse = sanitizeRuleResponse(ruleResponse);
    ruleResponse.policy.add = authorizationResults;
    return ruleResponse;
}
async function policyList(ruleResponse, databaseAdapter, context, options) {
    const listResponse = await (0, policy_1.listPolicyRule)(databaseAdapter, context, options);
    ruleResponse = sanitizeRuleResponse(ruleResponse);
    ruleResponse.policy.list = listResponse;
    return ruleResponse;
}
async function policyRemove(data, ruleResponse, databaseAdapter, context, options) {
    const removeResponse = await (0, policy_1.removePolicyRule)(data.ruleId, context, databaseAdapter, options);
    ruleResponse = sanitizeRuleResponse(ruleResponse);
    ruleResponse.policy.remove = removeResponse;
    return ruleResponse;
}
async function policyRule(action, data, ruleResponse, databaseAdapter, context, options) {
    if (!(context && context.useMasterKey === true)) {
        throw { message: 'policy rule require masterKey' };
    }
    if (action === 'add' && typeof data === 'object') {
        return await policyAdd(data, ruleResponse, databaseAdapter, context, options);
    }
    else if (action === 'list' && typeof data === 'object') {
        return await policyList(ruleResponse, databaseAdapter, context, options);
    }
    else if (action === 'remove' && typeof data === 'object') {
        return await policyRemove(data, ruleResponse, databaseAdapter, context, options);
    }
    else
        return ruleResponse;
}
exports.policyRule = policyRule;
