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_MAX from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/Team";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import ObjectID from "../../Types/ObjectID";
import PositiveNumber from "../../Types/PositiveNumber";
import TeamMemberService from "./TeamMemberService";
import ProjectSCIMService from "./ProjectSCIMService";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async getTeamsUserIsAPartOf(data) {
        const teamMembers = await TeamMemberService.findBy({
            query: {
                userId: data.userId,
                projectId: data.projectId,
            },
            select: {
                team: {
                    name: true,
                    _id: true,
                },
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
        });
        const teams = [];
        for (const teamMember of teamMembers) {
            if (teamMember.team) {
                teams.push(teamMember.team);
            }
        }
        return teams;
    }
    async assertScimAllowsTeamMutation(data) {
        if (!data.projectIds || data.projectIds.length === 0) {
            return;
        }
        const uniqueProjectIds = new Map();
        for (const projectId of data.projectIds) {
            if (projectId) {
                uniqueProjectIds.set(projectId.toString(), new ObjectID(projectId));
            }
        }
        for (const projectId of uniqueProjectIds.values()) {
            const scimCount = await ProjectSCIMService.countBy({
                query: {
                    projectId: projectId,
                    enablePushGroups: true,
                },
                skip: new PositiveNumber(0),
                limit: new PositiveNumber(1),
                props: {
                    isRoot: true,
                    tenantId: projectId,
                },
            });
            if (scimCount.toNumber() > 0) {
                throw new BadDataException(`Cannot ${data.action} teams while SCIM Push Groups is enabled for this project. Disable Push Groups to manage teams from OneUptime.`);
            }
        }
    }
    async onBeforeCreate(createBy) {
        let projectId = createBy.data.projectId;
        if (!projectId && createBy.props.tenantId) {
            projectId = new ObjectID(createBy.props.tenantId);
        }
        if (!projectId) {
            throw new BadDataException("Project ID cannot be null");
        }
        projectId = new ObjectID(projectId);
        createBy.data.projectId = projectId;
        if (!createBy.props.isRoot) {
            await this.assertScimAllowsTeamMutation({
                projectIds: [projectId],
                action: "create",
            });
        }
        return { createBy, carryForward: null };
    }
    async onBeforeUpdate(updateBy) {
        // get teams by query.
        const teams = await this.findBy({
            query: updateBy.query,
            limit: LIMIT_MAX,
            skip: 0,
            select: {
                name: true,
                isTeamEditable: true,
            },
            props: updateBy.props,
        });
        for (const team of teams) {
            if (!team.isTeamEditable) {
                throw new BadDataException(`${team.name || "This"} team cannot be updated because its a critical team for this project.`);
            }
        }
        return { updateBy, carryForward: null };
    }
    async onBeforeDelete(deleteBy) {
        const teams = await this.findBy({
            query: deleteBy.query,
            limit: LIMIT_MAX,
            skip: 0,
            select: {
                name: true,
                isTeamDeleteable: true,
                projectId: true,
            },
            props: deleteBy.props,
        });
        const projectIds = teams
            .map((team) => {
            return team.projectId;
        })
            .filter((projectId) => {
            return Boolean(projectId);
        });
        if (deleteBy.props.isRoot !== true) {
            await this.assertScimAllowsTeamMutation({
                projectIds: projectIds,
                action: "delete",
            });
        }
        for (const team of teams) {
            if (!team.isTeamDeleteable) {
                throw new BadDataException(`${team.name || "This"} team cannot be deleted its a critical team for this project.`);
            }
        }
        return { deleteBy, 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);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeDelete", null);
export default new Service();
//# sourceMappingURL=TeamService.js.map