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 AccessTokenService from "./AccessTokenService";
import DatabaseService from "./DatabaseService";
import TeamMemberService from "./TeamMemberService";
import TeamService from "./TeamService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import LIMIT_MAX, { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/TeamPermission";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        var _a;
        if (!createBy.data.teamId) {
            throw new BadDataException("Team 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");
        }
        // get team.
        const team = await TeamService.findOneById({
            id: createBy.data.teamId,
            select: {
                isPermissionsEditable: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!team) {
            throw new BadDataException("Invalid Team ID");
        }
        if (!team.isPermissionsEditable) {
            throw new BadDataException("You cannot create new permissions for this team because this team is not editable");
        }
        // 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: {
                teamId: createBy.data.teamId,
                projectId: createBy.data.projectId,
                permission: createBy.data.permission,
                isBlockPermission: isBlockPermission,
            },
            select: {
                _id: true,
                isBlockPermission: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (existingPermission) {
            throw new BadDataException("This permission is already assigned to this team.");
        }
        if (createBy.data.labels && createBy.data.labels.length > 0) {
            // check if the
            const existingPermission = await this.findOneBy({
                query: {
                    teamId: createBy.data.teamId,
                    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 onCreateSuccess(onCreate, createdItem) {
        const createBy = onCreate.createBy;
        const teamMembers = await TeamMemberService.findBy({
            query: {
                teamId: createBy.data.teamId,
            },
            select: {
                userId: true,
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_MAX,
            skip: 0,
        });
        for (const member of teamMembers) {
            /// Refresh tokens.
            await AccessTokenService.refreshUserGlobalAccessPermission(member.userId);
            await AccessTokenService.refreshUserTenantAccessPermission(member.userId, createBy.data.projectId);
        }
        return createdItem;
    }
    async onBeforeUpdate(updateBy) {
        var _a, _b;
        const teamPermissions = await this.findBy({
            query: updateBy.query,
            select: {
                _id: true,
                teamId: true,
                projectId: true,
                team: {
                    isPermissionsEditable: true,
                },
            },
            skip: 0,
            limit: LIMIT_MAX,
            props: {
                isRoot: true,
            },
        });
        for (const permission of teamPermissions) {
            if (!((_a = permission.team) === null || _a === void 0 ? void 0 : _a.isPermissionsEditable)) {
                throw new BadDataException("Permissions for this team is not updateable. You can create a new team and add permissions to that team instead.");
            }
        }
        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,
                    teamId: 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: {
                        teamId: alreadySavedPermission.teamId,
                        projectId: alreadySavedPermission.projectId,
                        permission: alreadySavedPermission.permission,
                        isBlockPermission: !isBlockPermission,
                    },
                    select: {
                        _id: true,
                        isBlockPermission: true,
                        labels: true,
                        permission: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (existingPermission &&
                    (((_b = existingPermission.labels) === null || _b === void 0 ? void 0 : _b.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: teamPermissions };
    }
    async onUpdateSuccess(onUpdate, _updatedItemIds) {
        for (const permission of onUpdate.carryForward) {
            const teamMembers = await TeamMemberService.findBy({
                query: {
                    teamId: permission.teamId,
                },
                select: {
                    userId: true,
                    projectId: true,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
            for (const member of teamMembers) {
                if (!member.userId) {
                    throw new BadDataException("Invalid User ID");
                }
                if (!member.projectId) {
                    throw new BadDataException("Invalid Project ID");
                }
                /// Refresh tokens.
                await AccessTokenService.refreshUserGlobalAccessPermission(member.userId);
                await AccessTokenService.refreshUserTenantAccessPermission(member.userId, member.projectId);
            }
        }
        return onUpdate;
    }
    async onBeforeDelete(deleteBy) {
        var _a;
        const teamPermissions = await this.findBy({
            query: deleteBy.query,
            select: {
                _id: true,
                teamId: true,
                projectId: true,
                team: {
                    isPermissionsEditable: true,
                },
            },
            skip: 0,
            limit: LIMIT_MAX,
            props: {
                isRoot: true,
            },
        });
        for (const permission of teamPermissions) {
            if (!((_a = permission.team) === null || _a === void 0 ? void 0 : _a.isPermissionsEditable)) {
                throw new BadDataException("Permissions for this team is not deleteable. You can create a new team and add permissions to that team instead.");
            }
        }
        let teamMembers = [];
        for (const permission of teamPermissions) {
            const members = await TeamMemberService.findBy({
                query: {
                    teamId: permission.teamId,
                },
                select: {
                    userId: true,
                    projectId: true,
                },
                props: {
                    isRoot: true,
                },
                limit: LIMIT_MAX,
                skip: 0,
            });
            teamMembers = teamMembers.concat(members);
        }
        return { deleteBy, carryForward: teamMembers };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        for (const member of onDelete.carryForward) {
            const teamMember = member;
            if (!teamMember.userId) {
                throw new BadDataException("Invalid User ID");
            }
            if (!teamMember.projectId) {
                throw new BadDataException("Invalid Project ID");
            }
            /// Refresh tokens.
            await AccessTokenService.refreshUserGlobalAccessPermission(teamMember.userId);
            await AccessTokenService.refreshUserTenantAccessPermission(teamMember.userId, teamMember.projectId);
        }
        return onDelete;
    }
}
__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, Model]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onCreateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onUpdateSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeDelete", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onDeleteSuccess", null);
export default new Service();
//# sourceMappingURL=TeamPermissionService.js.map