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);
};
import DatabaseService from "./DatabaseService";
import { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/ApiKeyPermission";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        var _a;
        if (!createBy.data.apiKeyId) {
            throw new BadDataException("API Key ID is required to create permission");
        }
        if (!createBy.data.projectId) {
            throw new BadDataException("Project Id is required to create permission");
        }
        if (!createBy.data.permission) {
            throw new BadDataException("Permission is required to create permission");
        }
        // check if this permission is already assigned to this team and if yes then throw error.
        const isBlockPermission = createBy.data.isBlockPermission || false;
        const existingPermission = await this.findOneBy({
            query: {
                apiKeyId: createBy.data.apiKeyId,
                projectId: createBy.data.projectId,
                permission: createBy.data.permission,
                isBlockPermission: isBlockPermission,
            },
            select: {
                _id: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (existingPermission) {
            throw new BadDataException("This permission is already assigned to this API Key");
        }
        if (createBy.data.labels && createBy.data.labels.length > 0) {
            // check if the
            const existingPermission = await this.findOneBy({
                query: {
                    apiKeyId: createBy.data.apiKeyId,
                    projectId: createBy.data.projectId,
                    permission: createBy.data.permission,
                    isBlockPermission: !isBlockPermission,
                },
                select: {
                    _id: true,
                    isBlockPermission: true,
                    labels: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (existingPermission && (((_a = existingPermission.labels) === null || _a === void 0 ? void 0 : _a.length) || 0) > 0) {
                // if the permission in another block has labels, this permission cannot have labels.
                const blockName = existingPermission.isBlockPermission
                    ? "block"
                    : "allow";
                throw new BadDataException(`Restriction labels are already assigned to this permission in the ${blockName} permission list. To assign restriction labels to this permission, remove the restriction labels from the ${blockName} permission`);
            }
        }
        return { createBy, carryForward: null };
    }
    async onBeforeUpdate(updateBy) {
        var _a;
        if (updateBy.data.labels && updateBy.data.labels.length > 0) {
            const existingPermissions = await this.findBy({
                query: updateBy.query,
                select: {
                    _id: true,
                    labels: true,
                    isBlockPermission: true,
                    projectId: true,
                    apiKeyId: true,
                    permission: true,
                },
                limit: LIMIT_PER_PROJECT,
                skip: 0,
                props: {
                    isRoot: true,
                },
            });
            for (const alreadySavedPermission of existingPermissions) {
                // check if the
                const isBlockPermission = alreadySavedPermission.isBlockPermission || false;
                const existingPermission = await this.findOneBy({
                    query: {
                        apiKeyId: alreadySavedPermission.apiKeyId,
                        projectId: alreadySavedPermission.projectId,
                        permission: alreadySavedPermission.permission,
                        isBlockPermission: !isBlockPermission,
                    },
                    select: {
                        _id: true,
                        isBlockPermission: true,
                        labels: true,
                        permission: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (existingPermission &&
                    (((_a = existingPermission.labels) === null || _a === void 0 ? void 0 : _a.length) || 0) > 0) {
                    // if the permission in another block has labels, this permission cannot have labels.
                    const blockName = existingPermission.isBlockPermission
                        ? "block"
                        : "allow";
                    throw new BadDataException(`Restriction labels are already assigned to ${existingPermission.permission} in the ${blockName} permission list. To assign restriction labels to this permission, remove the restriction labels from the ${blockName} list.`);
                }
            }
        }
        return { updateBy, carryForward: null };
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
export default new Service();
//# sourceMappingURL=ApiKeyPermissionService.js.map