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 OnCallDutyPolicySchedule from "../../Models/DatabaseModels/OnCallDutyPolicySchedule";
import OnCallDutyPolicyScheduleOwnerUser from "../../Models/DatabaseModels/OnCallDutyPolicyScheduleOwnerUser";
import OnCallDutyPolicyScheduleOwnerTeam from "../../Models/DatabaseModels/OnCallDutyPolicyScheduleOwnerTeam";
import OnCallDutyPolicyScheduleOwnerRuleService from "./OnCallDutyPolicyScheduleOwnerRuleService";
import OnCallDutyPolicyScheduleOwnerUserService from "./OnCallDutyPolicyScheduleOwnerUserService";
import OnCallDutyPolicyScheduleOwnerTeamService from "./OnCallDutyPolicyScheduleOwnerTeamService";
import OnCallDutyPolicyScheduleService from "./OnCallDutyPolicyScheduleService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class OnCallDutyPolicyScheduleOwnerRuleEngineServiceClass {
    async applyRulesToSchedule(schedule) {
        var _a, _b;
        if (!schedule.id || !schedule.projectId) {
            return;
        }
        try {
            const rules = await OnCallDutyPolicyScheduleOwnerRuleService.findBy({
                query: {
                    projectId: schedule.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    onCallDutyPolicyScheduleLabels: { _id: true },
                    onCallDutyPolicyScheduleNamePattern: true,
                    onCallDutyPolicyScheduleDescriptionPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const scheduleWithDetails = await OnCallDutyPolicyScheduleService.findOneById({
                id: schedule.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!scheduleWithDetails) {
                return;
            }
            const usersByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const teamsByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const matchedRules = [];
            for (const rule of rules) {
                const matches = this.doesScheduleMatchRule(scheduleWithDetails, rule);
                if (!matches) {
                    continue;
                }
                let ruleAddedAny = false;
                const notify = rule.notifyOwners !== false;
                for (const user of rule.ownerUsers || []) {
                    if (user.id) {
                        usersByNotify.get(notify).add(user.id.toString());
                        ruleAddedAny = true;
                    }
                }
                for (const team of rule.ownerTeams || []) {
                    if (team.id) {
                        teamsByNotify.get(notify).add(team.id.toString());
                        ruleAddedAny = true;
                    }
                }
                if (ruleAddedAny) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return;
            }
            for (const notify of [true, false]) {
                const userIds = usersByNotify.get(notify);
                const teamIds = teamsByNotify.get(notify);
                for (const userId of userIds) {
                    const owner = new OnCallDutyPolicyScheduleOwnerUser();
                    owner.onCallDutyPolicyScheduleId = schedule.id;
                    owner.projectId = schedule.projectId;
                    owner.userId = new ObjectID(userId);
                    owner.isOwnerNotified = !notify;
                    await OnCallDutyPolicyScheduleOwnerUserService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
                for (const teamId of teamIds) {
                    const owner = new OnCallDutyPolicyScheduleOwnerTeam();
                    owner.onCallDutyPolicyScheduleId = schedule.id;
                    owner.projectId = schedule.projectId;
                    owner.teamId = new ObjectID(teamId);
                    owner.isOwnerNotified = !notify;
                    await OnCallDutyPolicyScheduleOwnerTeamService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
            }
            logger.debug(`OnCallDutyPolicyScheduleOwnerRuleEngine added owners to schedule ${schedule.id}`, { projectId: schedule.projectId.toString() });
        }
        catch (error) {
            logger.error(`Error applying on-call duty schedule owner rules: ${error}`, {
                projectId: (_a = schedule.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                onCallDutyPolicyScheduleId: (_b = schedule.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesScheduleMatchRule(schedule, rule) {
        if (rule.onCallDutyPolicyScheduleLabels &&
            rule.onCallDutyPolicyScheduleLabels.length > 0) {
            if (!schedule.labels || schedule.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.onCallDutyPolicyScheduleLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const labelIds = schedule.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return labelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.onCallDutyPolicyScheduleNamePattern &&
            (!schedule.name ||
                !this.testRegex(rule.onCallDutyPolicyScheduleNamePattern, schedule.name, rule))) {
            return false;
        }
        if (rule.onCallDutyPolicyScheduleDescriptionPattern &&
            (!schedule.description ||
                !this.testRegex(rule.onCallDutyPolicyScheduleDescriptionPattern, schedule.description, rule))) {
            return false;
        }
        return true;
    }
    testRegex(pattern, value, rule) {
        try {
            const regex = new RegExp(pattern, "i");
            return regex.test(value);
        }
        catch (_a) {
            logger.warn(`Invalid regex in on-call duty schedule owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [OnCallDutyPolicySchedule]),
    __metadata("design:returntype", Promise)
], OnCallDutyPolicyScheduleOwnerRuleEngineServiceClass.prototype, "applyRulesToSchedule", null);
export default new OnCallDutyPolicyScheduleOwnerRuleEngineServiceClass();
//# sourceMappingURL=OnCallDutyPolicyScheduleOwnerRuleEngineService.js.map