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);
};
var _a;
import { IsBillingEnabled, getAllEnvVars, } from "../../../../Server/EnvironmentConfig";
import DatabaseRequestType from "../../BaseDatabase/DatabaseRequestType";
import DatabaseCommonInteractionPropsUtil, { PermissionType, } from "../../../../Types/BaseDatabase/DatabaseCommonInteractionPropsUtil";
import SubscriptionPlan from "../../../../Types/Billing/SubscriptionPlan";
import Columns from "../../../../Types/Database/Columns";
import TableColumnType from "../../../../Types/Database/TableColumnType";
import BadDataException from "../../../../Types/Exception/BadDataException";
import PaymentRequiredException from "../../../../Types/Exception/PaymentRequiredException";
import { PermissionHelper, } from "../../../../Types/Permission";
import CaptureSpan from "../../../Utils/Telemetry/CaptureSpan";
import logger from "../../../Utils/Logger";
export default class ColumnPermissions {
    static getExcludedColumnNames() {
        const returnArr = [
            "_id",
            "createdAt",
            "deletedAt",
            "updatedAt",
            "version",
        ];
        return returnArr;
    }
    static getModelColumnsByPermissions(modelType, userPermissions, requestType) {
        var _a, _b, _c;
        const model = new modelType();
        const accessControl = model.getColumnAccessControlForAllColumns();
        const columns = [];
        const permissions = userPermissions.map((item) => {
            return item.permission;
        });
        for (const key in accessControl) {
            let columnPermissions = [];
            if (requestType === DatabaseRequestType.Read) {
                columnPermissions = ((_a = accessControl[key]) === null || _a === void 0 ? void 0 : _a.read) || [];
            }
            if (requestType === DatabaseRequestType.Create) {
                columnPermissions = ((_b = accessControl[key]) === null || _b === void 0 ? void 0 : _b.create) || [];
            }
            if (requestType === DatabaseRequestType.Update) {
                columnPermissions = ((_c = accessControl[key]) === null || _c === void 0 ? void 0 : _c.update) || [];
            }
            if (requestType === DatabaseRequestType.Delete) {
                throw new BadDataException("Invalid request type delete");
            }
            if (columnPermissions &&
                PermissionHelper.doesPermissionsIntersect(permissions, columnPermissions)) {
                columns.push(key);
            }
        }
        return new Columns(columns);
    }
    static checkDataColumnPermissions(modelType, data, props, requestType) {
        const model = new modelType();
        const userPermissions = DatabaseCommonInteractionPropsUtil.getUserPermissions(props, PermissionType.Allow);
        const permissionColumns = this.getModelColumnsByPermissions(modelType, userPermissions, requestType);
        const excludedColumnNames = this.getExcludedColumnNames();
        const tableColumns = model.getTableColumns().columns;
        for (const key of Object.keys(data)) {
            if (data[key] === undefined) {
                continue;
            }
            if (excludedColumnNames.includes(key)) {
                continue;
            }
            if (!tableColumns.includes(key)) {
                continue;
            }
            const tableColumnMetadata = model.getTableColumnMetadata(key);
            if (!tableColumnMetadata) {
                throw new BadDataException(`No TableColumnMetadata found for ${key} column of ${model.singularName}`);
            }
            if (tableColumnMetadata.type === TableColumnType.Slug) {
                continue;
            }
            if (!permissionColumns.columns.includes(key) &&
                tableColumns.includes(key)) {
                if (requestType === DatabaseRequestType.Create &&
                    tableColumnMetadata.forceGetDefaultValueOnCreate) {
                    continue; // this is a special case where we want to force the default value on create.
                }
                if (requestType === DatabaseRequestType.Create &&
                    tableColumnMetadata.computed) {
                    continue; // computed columns are not allowed to be updated.
                }
                throw new BadDataException(`User is not allowed to ${requestType} on ${key} column of ${model.singularName}`);
            }
            if (IsBillingEnabled &&
                props.currentPlan &&
                model.getColumnBillingAccessControl(key)) {
                const billingAccessControl = model.getColumnBillingAccessControl(key);
                if (requestType === DatabaseRequestType.Create &&
                    billingAccessControl.create) {
                    if (!SubscriptionPlan.isFeatureAccessibleOnCurrentPlan(billingAccessControl.create, props.currentPlan, getAllEnvVars())) {
                        throw new PaymentRequiredException("Please upgrade your plan to " +
                            billingAccessControl.create +
                            " to access this feature");
                    }
                }
                if (requestType === DatabaseRequestType.Read &&
                    billingAccessControl.read) {
                    if (!SubscriptionPlan.isFeatureAccessibleOnCurrentPlan(billingAccessControl.read, props.currentPlan, getAllEnvVars())) {
                        throw new PaymentRequiredException("Please upgrade your plan to " +
                            billingAccessControl.read +
                            " to access this feature");
                    }
                }
                if (requestType === DatabaseRequestType.Update &&
                    billingAccessControl.update) {
                    if (!SubscriptionPlan.isFeatureAccessibleOnCurrentPlan(billingAccessControl.update, props.currentPlan, getAllEnvVars())) {
                        logger.debug(`User does not have access to update ${key} column of ${model.singularName}`);
                        throw new PaymentRequiredException("Please upgrade your plan to " +
                            billingAccessControl.update +
                            " to access this feature");
                    }
                }
            }
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Array)
], ColumnPermissions, "getExcludedColumnNames", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array, String]),
    __metadata("design:returntype", Columns)
], ColumnPermissions, "getModelColumnsByPermissions", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, typeof (_a = typeof TBaseModel !== "undefined" && TBaseModel) === "function" ? _a : Object, Object, String]),
    __metadata("design:returntype", void 0)
], ColumnPermissions, "checkDataColumnPermissions", null);
//# sourceMappingURL=ColumnPermission.js.map