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 StatusPage from "../../Models/DatabaseModels/StatusPage";
import StatusPageOwnerRuleService from "./StatusPageOwnerRuleService";
import StatusPageService from "./StatusPageService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class StatusPageOwnerRuleEngineServiceClass {
    /**
     * Evaluates StatusPageOwnerRule rows for the given status page and adds
     * matched owner users / teams via StatusPageService.addOwners. Rules with
     * notifyOwners set notify the added owners; rules with notifyOwners off
     * add silently.
     */
    async applyRulesToStatusPage(statusPage) {
        var _a, _b;
        if (!statusPage.id || !statusPage.projectId) {
            return;
        }
        try {
            const rules = await StatusPageOwnerRuleService.findBy({
                query: {
                    projectId: statusPage.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    statusPageLabels: { _id: true },
                    statusPageNamePattern: true,
                    statusPageDescriptionPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const usersByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const teamsByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const matchedRules = [];
            const allUserIds = new Set();
            const allTeamIds = new Set();
            const statusPageWithDetails = await StatusPageService.findOneById({
                id: statusPage.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!statusPageWithDetails) {
                return;
            }
            for (const rule of rules) {
                const matches = this.doesStatusPageMatchRule(statusPageWithDetails, 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());
                        allUserIds.add(user.id.toString());
                        ruleAddedAny = true;
                    }
                }
                for (const team of rule.ownerTeams || []) {
                    if (team.id) {
                        teamsByNotify.get(notify).add(team.id.toString());
                        allTeamIds.add(team.id.toString());
                        ruleAddedAny = true;
                    }
                }
                if (ruleAddedAny) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return;
            }
            if (allUserIds.size === 0 && allTeamIds.size === 0) {
                return;
            }
            for (const notify of [true, false]) {
                const userIds = Array.from(usersByNotify.get(notify)).map((id) => {
                    return new ObjectID(id);
                });
                const teamIds = Array.from(teamsByNotify.get(notify)).map((id) => {
                    return new ObjectID(id);
                });
                if (userIds.length === 0 && teamIds.length === 0) {
                    continue;
                }
                await StatusPageService.addOwners(statusPage.projectId, statusPage.id, userIds, teamIds, notify, { isRoot: true });
            }
            logger.debug(`StatusPageOwnerRuleEngine added owners to status page ${statusPage.id}`, { projectId: statusPage.projectId.toString() });
        }
        catch (error) {
            logger.error(`Error applying status page owner rules: ${error}`, {
                projectId: (_a = statusPage.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                statusPageId: (_b = statusPage.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesStatusPageMatchRule(statusPage, rule) {
        if (rule.statusPageLabels && rule.statusPageLabels.length > 0) {
            if (!statusPage.labels || statusPage.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.statusPageLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const statusPageLabelIds = statusPage.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return statusPageLabelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.statusPageNamePattern &&
            (!statusPage.name ||
                !this.testRegex(rule.statusPageNamePattern, statusPage.name, rule))) {
            return false;
        }
        if (rule.statusPageDescriptionPattern &&
            (!statusPage.description ||
                !this.testRegex(rule.statusPageDescriptionPattern, statusPage.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 status page owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [StatusPage]),
    __metadata("design:returntype", Promise)
], StatusPageOwnerRuleEngineServiceClass.prototype, "applyRulesToStatusPage", null);
export default new StatusPageOwnerRuleEngineServiceClass();
//# sourceMappingURL=StatusPageOwnerRuleEngineService.js.map