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 Alert from "../../Models/DatabaseModels/Alert";
import AlertOwnerRule from "../../Models/DatabaseModels/AlertOwnerRule";
import AlertFeedService from "./AlertFeedService";
import AlertOwnerRuleService from "./AlertOwnerRuleService";
import AlertService from "./AlertService";
import DockerHostOwnerTeamService from "./DockerHostOwnerTeamService";
import DockerHostOwnerUserService from "./DockerHostOwnerUserService";
import HostOwnerTeamService from "./HostOwnerTeamService";
import HostOwnerUserService from "./HostOwnerUserService";
import KubernetesClusterOwnerTeamService from "./KubernetesClusterOwnerTeamService";
import KubernetesClusterOwnerUserService from "./KubernetesClusterOwnerUserService";
import MonitorOwnerTeamService from "./MonitorOwnerTeamService";
import MonitorOwnerUserService from "./MonitorOwnerUserService";
import MonitorService from "./MonitorService";
import ServiceOwnerTeamService from "./ServiceOwnerTeamService";
import ServiceOwnerUserService from "./ServiceOwnerUserService";
import TeamService from "./TeamService";
import UserService from "./UserService";
import { AlertFeedEventType } from "../../Models/DatabaseModels/AlertFeed";
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 AlertOwnerRuleEngineServiceClass {
    /**
     * Evaluates AlertOwnerRule rows for the given alert and adds matched
     * owner users / teams via AlertService.addOwners.
     */
    async applyRulesToAlert(alert) {
        var _a, _b, _c, _d, _e, _f;
        if (!alert.id || !alert.projectId) {
            return;
        }
        try {
            const rules = await AlertOwnerRuleService.findBy({
                query: {
                    projectId: alert.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    monitors: { _id: true },
                    alertSeverities: { _id: true },
                    alertLabels: { _id: true },
                    monitorLabels: { _id: true },
                    alertTitlePattern: true,
                    alertDescriptionPattern: true,
                    monitorNamePattern: true,
                    monitorDescriptionPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                    inheritOwnersFromMonitors: true,
                    inheritOwnersFromHosts: true,
                    inheritOwnersFromKubernetesClusters: true,
                    inheritOwnersFromDockerHosts: true,
                    inheritOwnersFromServices: 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();
            let inheritFromMonitors = false;
            let inheritFromHosts = false;
            let inheritFromKubernetesClusters = false;
            let inheritFromDockerHosts = false;
            let inheritFromServices = false;
            const inheritNotifyMode = { value: null };
            for (const rule of rules) {
                const matches = await this.doesAlertMatchRule(alert, 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 (rule.inheritOwnersFromMonitors) {
                    inheritFromMonitors = true;
                    ruleAddedAny = true;
                    inheritNotifyMode.value =
                        inheritNotifyMode.value === true ? true : notify;
                }
                if (rule.inheritOwnersFromHosts) {
                    inheritFromHosts = true;
                    ruleAddedAny = true;
                    inheritNotifyMode.value =
                        inheritNotifyMode.value === true ? true : notify;
                }
                if (rule.inheritOwnersFromKubernetesClusters) {
                    inheritFromKubernetesClusters = true;
                    ruleAddedAny = true;
                    inheritNotifyMode.value =
                        inheritNotifyMode.value === true ? true : notify;
                }
                if (rule.inheritOwnersFromDockerHosts) {
                    inheritFromDockerHosts = true;
                    ruleAddedAny = true;
                    inheritNotifyMode.value =
                        inheritNotifyMode.value === true ? true : notify;
                }
                if (rule.inheritOwnersFromServices) {
                    inheritFromServices = true;
                    ruleAddedAny = true;
                    inheritNotifyMode.value =
                        inheritNotifyMode.value === true ? true : notify;
                }
                if (ruleAddedAny) {
                    matchedRules.push(rule);
                }
            }
            const inheritedFromMonitorUserIds = new Set();
            const inheritedFromMonitorTeamIds = new Set();
            const inheritedFromHostUserIds = new Set();
            const inheritedFromHostTeamIds = new Set();
            const inheritedFromKubernetesClusterUserIds = new Set();
            const inheritedFromKubernetesClusterTeamIds = new Set();
            const inheritedFromDockerHostUserIds = new Set();
            const inheritedFromDockerHostTeamIds = new Set();
            const inheritedFromServiceUserIds = new Set();
            const inheritedFromServiceTeamIds = new Set();
            if (inheritFromMonitors && alert.monitorId) {
                const [monitorOwnerUsers, monitorOwnerTeams] = await Promise.all([
                    MonitorOwnerUserService.findBy({
                        query: { monitorId: alert.monitorId },
                        select: { userId: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    }),
                    MonitorOwnerTeamService.findBy({
                        query: { monitorId: alert.monitorId },
                        select: { teamId: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    }),
                ]);
                for (const ownerUser of monitorOwnerUsers) {
                    if (ownerUser.userId) {
                        inheritedFromMonitorUserIds.add(ownerUser.userId.toString());
                    }
                }
                for (const ownerTeam of monitorOwnerTeams) {
                    if (ownerTeam.teamId) {
                        inheritedFromMonitorTeamIds.add(ownerTeam.teamId.toString());
                    }
                }
            }
            if (inheritFromHosts && ((_a = alert.hosts) === null || _a === void 0 ? void 0 : _a.length)) {
                const hostIds = alert.hosts
                    .map((h) => {
                    return h.id;
                })
                    .filter((id) => {
                    return Boolean(id);
                });
                if (hostIds.length > 0) {
                    const [hostOwnerUsers, hostOwnerTeams] = await Promise.all([
                        HostOwnerUserService.findBy({
                            query: { hostId: QueryHelper.any(hostIds) },
                            select: { userId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                        HostOwnerTeamService.findBy({
                            query: { hostId: QueryHelper.any(hostIds) },
                            select: { teamId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                    ]);
                    for (const ownerUser of hostOwnerUsers) {
                        if (ownerUser.userId) {
                            inheritedFromHostUserIds.add(ownerUser.userId.toString());
                        }
                    }
                    for (const ownerTeam of hostOwnerTeams) {
                        if (ownerTeam.teamId) {
                            inheritedFromHostTeamIds.add(ownerTeam.teamId.toString());
                        }
                    }
                }
            }
            if (inheritFromKubernetesClusters && ((_b = alert.kubernetesClusters) === null || _b === void 0 ? void 0 : _b.length)) {
                const clusterIds = alert.kubernetesClusters
                    .map((c) => {
                    return c.id;
                })
                    .filter((id) => {
                    return Boolean(id);
                });
                if (clusterIds.length > 0) {
                    const [clusterOwnerUsers, clusterOwnerTeams] = await Promise.all([
                        KubernetesClusterOwnerUserService.findBy({
                            query: { kubernetesClusterId: QueryHelper.any(clusterIds) },
                            select: { userId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                        KubernetesClusterOwnerTeamService.findBy({
                            query: { kubernetesClusterId: QueryHelper.any(clusterIds) },
                            select: { teamId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                    ]);
                    for (const ownerUser of clusterOwnerUsers) {
                        if (ownerUser.userId) {
                            inheritedFromKubernetesClusterUserIds.add(ownerUser.userId.toString());
                        }
                    }
                    for (const ownerTeam of clusterOwnerTeams) {
                        if (ownerTeam.teamId) {
                            inheritedFromKubernetesClusterTeamIds.add(ownerTeam.teamId.toString());
                        }
                    }
                }
            }
            if (inheritFromDockerHosts && ((_c = alert.dockerHosts) === null || _c === void 0 ? void 0 : _c.length)) {
                const dockerHostIds = alert.dockerHosts
                    .map((d) => {
                    return d.id;
                })
                    .filter((id) => {
                    return Boolean(id);
                });
                if (dockerHostIds.length > 0) {
                    const [dockerHostOwnerUsers, dockerHostOwnerTeams] = await Promise.all([
                        DockerHostOwnerUserService.findBy({
                            query: { dockerHostId: QueryHelper.any(dockerHostIds) },
                            select: { userId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                        DockerHostOwnerTeamService.findBy({
                            query: { dockerHostId: QueryHelper.any(dockerHostIds) },
                            select: { teamId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                    ]);
                    for (const ownerUser of dockerHostOwnerUsers) {
                        if (ownerUser.userId) {
                            inheritedFromDockerHostUserIds.add(ownerUser.userId.toString());
                        }
                    }
                    for (const ownerTeam of dockerHostOwnerTeams) {
                        if (ownerTeam.teamId) {
                            inheritedFromDockerHostTeamIds.add(ownerTeam.teamId.toString());
                        }
                    }
                }
            }
            if (inheritFromServices && ((_d = alert.services) === null || _d === void 0 ? void 0 : _d.length)) {
                const serviceIds = alert.services
                    .map((s) => {
                    return s.id;
                })
                    .filter((id) => {
                    return Boolean(id);
                });
                if (serviceIds.length > 0) {
                    const [serviceOwnerUsers, serviceOwnerTeams] = await Promise.all([
                        ServiceOwnerUserService.findBy({
                            query: { serviceId: QueryHelper.any(serviceIds) },
                            select: { userId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                        ServiceOwnerTeamService.findBy({
                            query: { serviceId: QueryHelper.any(serviceIds) },
                            select: { teamId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                    ]);
                    for (const ownerUser of serviceOwnerUsers) {
                        if (ownerUser.userId) {
                            inheritedFromServiceUserIds.add(ownerUser.userId.toString());
                        }
                    }
                    for (const ownerTeam of serviceOwnerTeams) {
                        if (ownerTeam.teamId) {
                            inheritedFromServiceTeamIds.add(ownerTeam.teamId.toString());
                        }
                    }
                }
            }
            const inheritedUserIds = new Set([
                ...inheritedFromMonitorUserIds,
                ...inheritedFromHostUserIds,
                ...inheritedFromKubernetesClusterUserIds,
                ...inheritedFromDockerHostUserIds,
                ...inheritedFromServiceUserIds,
            ]);
            const inheritedTeamIds = new Set([
                ...inheritedFromMonitorTeamIds,
                ...inheritedFromHostTeamIds,
                ...inheritedFromKubernetesClusterTeamIds,
                ...inheritedFromDockerHostTeamIds,
                ...inheritedFromServiceTeamIds,
            ]);
            if (inheritedUserIds.size > 0 || inheritedTeamIds.size > 0) {
                const inheritNotify = inheritNotifyMode.value === true;
                for (const id of inheritedUserIds) {
                    usersByNotify.get(inheritNotify).add(id);
                    allUserIds.add(id);
                }
                for (const id of inheritedTeamIds) {
                    teamsByNotify.get(inheritNotify).add(id);
                    allTeamIds.add(id);
                }
            }
            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 AlertService.addOwners(alert.projectId, alert.id, userIds, teamIds, notify, { isRoot: true });
            }
            logger.debug(`AlertOwnerRuleEngine added owners to alert ${alert.id}`, {
                projectId: alert.projectId.toString(),
            });
            await this.createRuleExecutedFeedItem({
                alert,
                matchedRules,
                userIds: Array.from(allUserIds),
                teamIds: Array.from(allTeamIds),
                inheritedFromMonitors: inheritedFromMonitorUserIds.size + inheritedFromMonitorTeamIds.size >
                    0,
                inheritedFromHosts: inheritedFromHostUserIds.size + inheritedFromHostTeamIds.size > 0,
                inheritedFromKubernetesClusters: inheritedFromKubernetesClusterUserIds.size +
                    inheritedFromKubernetesClusterTeamIds.size >
                    0,
                inheritedFromDockerHosts: inheritedFromDockerHostUserIds.size +
                    inheritedFromDockerHostTeamIds.size >
                    0,
                inheritedFromServices: inheritedFromServiceUserIds.size + inheritedFromServiceTeamIds.size >
                    0,
            });
        }
        catch (error) {
            logger.error(`Error applying alert owner rules: ${error}`, {
                projectId: (_e = alert.projectId) === null || _e === void 0 ? void 0 : _e.toString(),
                alertId: (_f = alert.id) === null || _f === void 0 ? void 0 : _f.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { alert, matchedRules, userIds, teamIds, inheritedFromMonitors, inheritedFromHosts, inheritedFromKubernetesClusters, inheritedFromDockerHosts, inheritedFromServices, } = data;
        if (!alert.id ||
            !alert.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 inheritedSources = [];
            if (inheritedFromMonitors) {
                inheritedSources.push("monitor");
            }
            if (inheritedFromHosts) {
                inheritedSources.push("hosts");
            }
            if (inheritedFromKubernetesClusters) {
                inheritedSources.push("Kubernetes clusters");
            }
            if (inheritedFromDockerHosts) {
                inheritedSources.push("Docker hosts");
            }
            if (inheritedFromServices) {
                inheritedSources.push("services");
            }
            const inheritedNote = inheritedSources.length > 0
                ? `\n\n_Some owners were inherited from the alert's ${inheritedSources.join(", ")}._`
                : "";
            const feedInfoInMarkdown = `🛡️ **Alert Owner Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAssigned the following owner${userLines.length + teamLines.length === 1 ? "" : "s"} to the alert:${ownersPart}${inheritedNote}`;
            await AlertFeedService.createAlertFeedItem({
                alertId: alert.id,
                projectId: alert.projectId,
                alertFeedEventType: AlertFeedEventType.OwnerRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertOwnerRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = alert.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                alertId: (_b = alert.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesAlertMatchRule(alert, rule) {
        if (rule.monitors && rule.monitors.length > 0) {
            if (!alert.monitorId) {
                return false;
            }
            const ruleMonitorIds = rule.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleMonitorIds.includes(alert.monitorId.toString())) {
                return false;
            }
        }
        if (rule.alertSeverities && rule.alertSeverities.length > 0) {
            if (!alert.alertSeverityId) {
                return false;
            }
            const severityIds = rule.alertSeverities.map((s) => {
                var _a;
                return ((_a = s.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!severityIds.includes(alert.alertSeverityId.toString())) {
                return false;
            }
        }
        if (rule.alertLabels && rule.alertLabels.length > 0) {
            if (!alert.labels || alert.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.alertLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const alertLabelIds = alert.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return alertLabelIds.includes(id);
            })) {
                return false;
            }
        }
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!alert.monitorId) {
                return false;
            }
            const monitor = await MonitorService.findOneById({
                id: alert.monitorId,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!monitor) {
                return false;
            }
            if (rule.monitorLabels && rule.monitorLabels.length > 0) {
                if (!monitor.labels || monitor.labels.length === 0) {
                    return false;
                }
                const ruleMonitorLabelIds = 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 (!ruleMonitorLabelIds.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;
            }
        }
        if (rule.alertTitlePattern &&
            (!alert.title ||
                !this.testRegex(rule.alertTitlePattern, alert.title, rule))) {
            return false;
        }
        if (rule.alertDescriptionPattern &&
            (!alert.description ||
                !this.testRegex(rule.alertDescriptionPattern, alert.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 alert owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert]),
    __metadata("design:returntype", Promise)
], AlertOwnerRuleEngineServiceClass.prototype, "applyRulesToAlert", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertOwnerRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert,
        AlertOwnerRule]),
    __metadata("design:returntype", Promise)
], AlertOwnerRuleEngineServiceClass.prototype, "doesAlertMatchRule", null);
export default new AlertOwnerRuleEngineServiceClass();
//# sourceMappingURL=AlertOwnerRuleEngineService.js.map