"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleStorageRule = void 0;
const policy_1 = require("./policy");
const storage_1 = require("./storage");
async function checkFilePermission(action, context, databaseAdapter, options) {
    const allowed = await (0, policy_1.ruleHasPermission)(`files.${action}`, context, databaseAdapter, options);
    if (allowed !== true)
        throw { message: 'You have insufficient permission to this resource' };
}
async function saveFile(action, data, ruleResponse, context, filesAdapter, databaseAdapter, options) {
    await checkFilePermission(action, context, databaseAdapter, options);
    if (!ruleResponse.files)
        ruleResponse.files = {};
    ruleResponse.files.save = await (0, storage_1.saveFileInStore)(data, context, filesAdapter, options);
    return ruleResponse;
}
async function deleteFile(action, data, ruleResponse, context, filesAdapter, databaseAdapter, options) {
    await checkFilePermission(action, context, databaseAdapter, options);
    if (!ruleResponse.files)
        ruleResponse.files = {};
    ruleResponse.files.delete = await (0, storage_1.deleteFileInStore)(data, context, filesAdapter, options);
    return ruleResponse;
}
async function listFiles(action, data, ruleResponse, context, filesAdapter, databaseAdapter, options) {
    await checkFilePermission(action, context, databaseAdapter, options);
    if (!ruleResponse.files)
        ruleResponse.files = {};
    const listData = {
        prefix: data && data.prefix ? data.prefix : '',
        size: data && data.size ? data.size : 20,
        after: data && data.after ? data.after : null,
        skip: data && data.skip ? data.skip : 0
    };
    ruleResponse.files.list = await (0, storage_1.listFilesFromStore)(listData, filesAdapter, options);
    return ruleResponse;
}
async function handleStorageRule(file, ruleResponse, fileAdapter, databaseAdapter, context, options) {
    for (const action of Object.keys(file)) {
        const data = file[action];
        if (action === 'save')
            ruleResponse =
                await saveFile(action, data, ruleResponse, context, fileAdapter, databaseAdapter, options);
        if (action === 'delete')
            ruleResponse =
                await deleteFile(action, data, ruleResponse, context, fileAdapter, databaseAdapter, options);
        if (action === 'list')
            ruleResponse =
                await listFiles(action, data, ruleResponse, context, fileAdapter, databaseAdapter, options);
    }
    return ruleResponse;
}
exports.handleStorageRule = handleStorageRule;
