import DatabaseService from "./DatabaseService";
import BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/IncidentRole";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import ObjectID from "../../Types/ObjectID";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        // Primary roles cannot allow multiple users
        if (createBy.data.isPrimaryRole && createBy.data.canAssignMultipleUsers) {
            throw new BadDataException("Primary roles cannot allow multiple users to be assigned.");
        }
        return { createBy, carryForward: null };
    }
    async onBeforeUpdate(updateBy) {
        // If trying to set canAssignMultipleUsers to true, check if any of the roles are primary
        if (updateBy.data.canAssignMultipleUsers === true && updateBy.query._id) {
            // Convert _id to ObjectID if it's a string
            const id = updateBy.query._id instanceof ObjectID
                ? updateBy.query._id
                : new ObjectID(updateBy.query._id);
            const role = await this.findOneById({
                id: id,
                select: {
                    isPrimaryRole: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (role === null || role === void 0 ? void 0 : role.isPrimaryRole) {
                throw new BadDataException("Primary roles cannot allow multiple users to be assigned.");
            }
        }
        return { updateBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        const roles = await this.findBy({
            query: deleteBy.query,
            limit: LIMIT_MAX,
            skip: 0,
            select: {
                name: true,
                isDeleteable: true,
            },
            props: deleteBy.props,
        });
        for (const role of roles) {
            if (role.isDeleteable === false) {
                throw new BadDataException(`${role.name || "This"} role cannot be deleted because it is a required role for incident management.`);
            }
        }
        return { deleteBy, carryForward: null };
    }
}
export default new Service();
//# sourceMappingURL=IncidentRoleService.js.map