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 Monitor from "../../Models/DatabaseModels/Monitor";
import MonitorFeedService from "./MonitorFeedService";
import MonitorOwnerRuleService from "./MonitorOwnerRuleService";
import MonitorService from "./MonitorService";
import TeamService from "./TeamService";
import UserService from "./UserService";
import { MonitorFeedEventType } from "../../Models/DatabaseModels/MonitorFeed";
import { Indigo500 } from "../../Types/BrandColors";
import ObjectID from "../../Types/ObjectID";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import QueryHelper from "../Types/Database/QueryHelper";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class MonitorOwnerRuleEngineServiceClass {
    /**
     * Evaluates MonitorOwnerRule rows for the given monitor and adds matched
     * owner users / teams via MonitorService.addOwners. Rules with notifyOwners
     * set notify the added owners; rules with notifyOwners off add silently.
     */
    async applyRulesToMonitor(monitor) {
        var _a, _b;
        if (!monitor.id || !monitor.projectId) {
            return;
        }
        try {
            const rules = await MonitorOwnerRuleService.findBy({
                query: {
                    projectId: monitor.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    monitorLabels: { _id: true },
                    monitorNamePattern: true,
                    monitorDescriptionPattern: 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 monitorWithDetails = await MonitorService.findOneById({
                id: monitor.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!monitorWithDetails) {
                return;
            }
            for (const rule of rules) {
                const matches = this.doesMonitorMatchRule(monitorWithDetails, 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 MonitorService.addOwners(monitor.projectId, monitor.id, userIds, teamIds, notify, { isRoot: true });
            }
            logger.debug(`MonitorOwnerRuleEngine added owners to monitor ${monitor.id}`, { projectId: monitor.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                monitor,
                matchedRules,
                userIds: Array.from(allUserIds),
                teamIds: Array.from(allTeamIds),
            });
        }
        catch (error) {
            logger.error(`Error applying monitor owner rules: ${error}`, {
                projectId: (_a = monitor.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                monitorId: (_b = monitor.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { monitor, matchedRules, userIds, teamIds } = data;
        if (!monitor.id ||
            !monitor.projectId ||
            matchedRules.length === 0 ||
            (userIds.length === 0 && teamIds.length === 0)) {
            return;
        }
        try {
            const userObjectIds = userIds.map((id) => {
                return new ObjectID(id);
            });
            const teamObjectIds = teamIds.map((id) => {
                return new ObjectID(id);
            });
            const [users, teams] = await Promise.all([
                userObjectIds.length > 0
                    ? UserService.findBy({
                        query: { _id: QueryHelper.any(userObjectIds) },
                        select: { name: true, email: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    })
                    : Promise.resolve([]),
                teamObjectIds.length > 0
                    ? TeamService.findBy({
                        query: { _id: QueryHelper.any(teamObjectIds) },
                        select: { name: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    })
                    : Promise.resolve([]),
            ]);
            const userLines = users.map((u) => {
                var _a, _b;
                const display = ((_a = u.name) === null || _a === void 0 ? void 0 : _a.toString()) || ((_b = u.email) === null || _b === void 0 ? void 0 : _b.toString()) || "Unknown User";
                return `\n- 👤 ${display}`;
            });
            const teamLines = teams.map((t) => {
                var _a;
                return `\n- 👥 ${((_a = t.name) === null || _a === void 0 ? void 0 : _a.toString()) || "Unnamed Team"}`;
            });
            const ruleNames = matchedRules
                .map((r) => {
                var _a;
                return ((_a = r.name) === null || _a === void 0 ? void 0 : _a.toString()) || "Unnamed Rule";
            })
                .filter((n) => {
                return n !== "";
            });
            const rulesPart = ruleNames.length === 1
                ? `**${ruleNames[0]}**`
                : ruleNames
                    .map((n) => {
                    return `**${n}**`;
                })
                    .join(", ");
            const ownersPart = userLines.length + teamLines.length > 0
                ? userLines.concat(teamLines).join("")
                : "\n- (no named owners)";
            const feedInfoInMarkdown = `🛡️ **Monitor Owner Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAssigned the following owner${userLines.length + teamLines.length === 1 ? "" : "s"} to the monitor:${ownersPart}`;
            await MonitorFeedService.createMonitorFeedItem({
                monitorId: monitor.id,
                projectId: monitor.projectId,
                monitorFeedEventType: MonitorFeedEventType.OwnerRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`MonitorOwnerRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = monitor.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                monitorId: (_b = monitor.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesMonitorMatchRule(monitor, rule) {
        if (rule.monitorLabels && rule.monitorLabels.length > 0) {
            if (!monitor.labels || monitor.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.monitorLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const monitorLabelIds = monitor.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return monitorLabelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.monitorNamePattern &&
            (!monitor.name ||
                !this.testRegex(rule.monitorNamePattern, monitor.name, rule))) {
            return false;
        }
        if (rule.monitorDescriptionPattern &&
            (!monitor.description ||
                !this.testRegex(rule.monitorDescriptionPattern, monitor.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 monitor owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Monitor]),
    __metadata("design:returntype", Promise)
], MonitorOwnerRuleEngineServiceClass.prototype, "applyRulesToMonitor", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MonitorOwnerRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new MonitorOwnerRuleEngineServiceClass();
//# sourceMappingURL=MonitorOwnerRuleEngineService.js.map