"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.DataTableProxyService = void 0;
exports.isAllowedNode = isAllowedNode;
const backend_common_1 = require("@n8n/backend-common");
const di_1 = require("@n8n/di");
const data_table_aggregate_service_1 = require("./data-table-aggregate.service");
const data_table_service_1 = require("./data-table.service");
const forbidden_error_1 = require("../../errors/response-errors/forbidden.error");
const check_access_1 = require("../../permissions.ee/check-access");
const source_control_preferences_service_ee_1 = require("../../modules/source-control.ee/source-control-preferences.service.ee");
const ownership_service_1 = require("../../services/ownership.service");
const ALLOWED_NODES = [
    'n8n-nodes-base.dataTable',
    'n8n-nodes-base.dataTableTool',
    'n8n-nodes-base.evaluationTrigger',
    'n8n-nodes-base.evaluation',
];
function isAllowedNode(s) {
    return ALLOWED_NODES.includes(s);
}
let DataTableProxyService = class DataTableProxyService {
    constructor(dataTableService, dataTableAggregateService, ownershipService, logger, sourceControlPreferencesService) {
        this.dataTableService = dataTableService;
        this.dataTableAggregateService = dataTableAggregateService;
        this.ownershipService = ownershipService;
        this.logger = logger;
        this.sourceControlPreferencesService = sourceControlPreferencesService;
        this.logger = this.logger.scoped('data-table');
    }
    checkInstanceWriteAccess() {
        const preferences = this.sourceControlPreferencesService.getPreferences();
        if (preferences.branchReadOnly) {
            throw new forbidden_error_1.ForbiddenError('Cannot modify data tables on a protected instance. This instance is in read-only mode.');
        }
    }
    validateRequest(node) {
        if (!isAllowedNode(node.type)) {
            throw new Error('This proxy is only available for Data table nodes');
        }
    }
    async getProjectId(workflow) {
        const homeProject = await this.ownershipService.getWorkflowProjectCached(workflow.id);
        return homeProject.id;
    }
    async getDataTableAggregateProxy(workflow, node, projectId) {
        this.validateRequest(node);
        projectId = projectId ?? (await this.getProjectId(workflow));
        return this.makeAggregateOperations(projectId);
    }
    async getDataTableProxy(workflow, node, dataTableId, projectId) {
        this.validateRequest(node);
        projectId = projectId ?? (await this.getProjectId(workflow));
        return this.makeDataTableOperations(projectId, dataTableId);
    }
    async requireScope(user, scope, projectId) {
        const hasScope = await (0, check_access_1.userHasScopes)(user, [scope], false, { projectId });
        if (!hasScope) {
            throw new Error(`User does not have '${scope}' access on project '${projectId}'`);
        }
    }
    makeDataTableOperationsForUser(user) {
        const dataTableService = this.dataTableService;
        const dataTableAggregateService = this.dataTableAggregateService;
        const requireScope = async (scope, projectId) => await this.requireScope(user, scope, projectId);
        const checkInstanceWriteAccess = () => this.checkInstanceWriteAccess();
        return {
            async getManyAndCount(options) {
                return await dataTableAggregateService.getManyAndCount(user, options);
            },
            async createDataTable(projectId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:create', projectId);
                return await dataTableService.createDataTable(projectId, options);
            },
            async getColumns(dataTableId, projectId) {
                await requireScope('dataTable:read', projectId);
                return await dataTableService.getColumns(dataTableId, projectId);
            },
            async updateDataTable(dataTableId, projectId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:update', projectId);
                return await dataTableService.updateDataTable(dataTableId, projectId, options);
            },
            async addColumn(dataTableId, projectId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:update', projectId);
                return await dataTableService.addColumn(dataTableId, projectId, options);
            },
            async deleteColumn(dataTableId, projectId, columnId) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:update', projectId);
                return await dataTableService.deleteColumn(dataTableId, projectId, columnId);
            },
            async renameColumn(dataTableId, projectId, columnId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:update', projectId);
                return await dataTableService.renameColumn(dataTableId, projectId, columnId, options);
            },
            async deleteDataTable(dataTableId, projectId) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:delete', projectId);
                return await dataTableService.deleteDataTable(dataTableId, projectId);
            },
            async getManyRowsAndCount(dataTableId, projectId, options) {
                await requireScope('dataTable:readRow', projectId);
                return await dataTableService.getManyRowsAndCount(dataTableId, projectId, options);
            },
            async insertRows(dataTableId, projectId, rows, returnType) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:writeRow', projectId);
                return await dataTableService.insertRows(dataTableId, projectId, rows, returnType);
            },
            async updateRows(dataTableId, projectId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:writeRow', projectId);
                return await dataTableService.updateRows(dataTableId, projectId, { filter: options.filter, data: options.data }, true, options.dryRun);
            },
            async deleteRows(dataTableId, projectId, options) {
                checkInstanceWriteAccess();
                await requireScope('dataTable:writeRow', projectId);
                return await dataTableService.deleteRows(dataTableId, projectId, { filter: options.filter }, true, options.dryRun);
            },
        };
    }
    makeAggregateOperations(projectId) {
        const dataTableService = this.dataTableService;
        return {
            getProjectId() {
                return projectId;
            },
            async getManyAndCount(options = {}) {
                const serviceOptions = {
                    ...options,
                    filter: { projectId, ...(options.filter ?? {}) },
                };
                return await dataTableService.getManyAndCount(serviceOptions);
            },
            async createDataTable(options) {
                return await dataTableService.createDataTable(projectId, options);
            },
            async deleteDataTableAll() {
                return await dataTableService.deleteDataTableByProjectId(projectId);
            },
        };
    }
    makeDataTableOperations(projectId, dataTableId) {
        const dataTableService = this.dataTableService;
        return {
            async updateDataTable(options) {
                return await dataTableService.updateDataTable(dataTableId, projectId, options);
            },
            async deleteDataTable() {
                return await dataTableService.deleteDataTable(dataTableId, projectId);
            },
            async getColumns() {
                return await dataTableService.getColumns(dataTableId, projectId);
            },
            async addColumn(options) {
                return await dataTableService.addColumn(dataTableId, projectId, options);
            },
            async moveColumn(columnId, options) {
                return await dataTableService.moveColumn(dataTableId, projectId, columnId, options);
            },
            async deleteColumn(columnId) {
                return await dataTableService.deleteColumn(dataTableId, projectId, columnId);
            },
            async getManyRowsAndCount(options) {
                return await dataTableService.getManyRowsAndCount(dataTableId, projectId, options);
            },
            async insertRows(rows, returnType) {
                return await dataTableService.insertRows(dataTableId, projectId, rows, returnType);
            },
            async updateRows(options) {
                return await dataTableService.updateRows(dataTableId, projectId, { filter: options.filter, data: options.data }, true, options.dryRun);
            },
            async upsertRow(options) {
                return await dataTableService.upsertRow(dataTableId, projectId, options, true, options.dryRun);
            },
            async deleteRows(options) {
                return await dataTableService.deleteRows(dataTableId, projectId, { filter: options.filter }, true, options.dryRun);
            },
        };
    }
};
exports.DataTableProxyService = DataTableProxyService;
exports.DataTableProxyService = DataTableProxyService = __decorate([
    (0, di_1.Service)(),
    __metadata("design:paramtypes", [data_table_service_1.DataTableService,
        data_table_aggregate_service_1.DataTableAggregateService,
        ownership_service_1.OwnershipService,
        backend_common_1.Logger,
        source_control_preferences_service_ee_1.SourceControlPreferencesService])
], DataTableProxyService);
//# sourceMappingURL=data-table-proxy.service.js.map