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 ScheduledMaintenance from "../../Models/DatabaseModels/ScheduledMaintenance";
import ScheduledMaintenanceOwnerRule from "../../Models/DatabaseModels/ScheduledMaintenanceOwnerRule";
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 ScheduledMaintenanceFeedService from "./ScheduledMaintenanceFeedService";
import ScheduledMaintenanceOwnerRuleService from "./ScheduledMaintenanceOwnerRuleService";
import ScheduledMaintenanceService from "./ScheduledMaintenanceService";
import ServiceOwnerTeamService from "./ServiceOwnerTeamService";
import ServiceOwnerUserService from "./ServiceOwnerUserService";
import TeamService from "./TeamService";
import UserService from "./UserService";
import { ScheduledMaintenanceFeedEventType } from "../../Models/DatabaseModels/ScheduledMaintenanceFeed";
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 ScheduledMaintenanceOwnerRuleEngineServiceClass {
    /**
     * Evaluates ScheduledMaintenanceOwnerRule rows for the given event and adds
     * matched owner users / teams via ScheduledMaintenanceService.addOwners.
     * Rules with notifyOwners set notify the added owners; rules with
     * notifyOwners off add silently.
     */
    async applyRulesToScheduledMaintenance(scheduledMaintenance) {
        var _a, _b, _c, _d, _e, _f, _g;
        if (!scheduledMaintenance.id || !scheduledMaintenance.projectId) {
            return;
        }
        try {
            const rules = await ScheduledMaintenanceOwnerRuleService.findBy({
                query: {
                    projectId: scheduledMaintenance.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    monitors: { _id: true },
                    scheduledMaintenanceLabels: { _id: true },
                    monitorLabels: { _id: true },
                    titlePattern: true,
                    descriptionPattern: 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.doesScheduledMaintenanceMatchRule(scheduledMaintenance, 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 && ((_a = scheduledMaintenance.monitors) === null || _a === void 0 ? void 0 : _a.length)) {
                const monitorIds = scheduledMaintenance.monitors
                    .map((m) => {
                    return m.id;
                })
                    .filter((id) => {
                    return Boolean(id);
                });
                if (monitorIds.length > 0) {
                    const [monitorOwnerUsers, monitorOwnerTeams] = await Promise.all([
                        MonitorOwnerUserService.findBy({
                            query: { monitorId: QueryHelper.any(monitorIds) },
                            select: { userId: true },
                            props: { isRoot: true },
                            limit: LIMIT_MAX,
                            skip: 0,
                        }),
                        MonitorOwnerTeamService.findBy({
                            query: { monitorId: QueryHelper.any(monitorIds) },
                            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 && ((_b = scheduledMaintenance.hosts) === null || _b === void 0 ? void 0 : _b.length)) {
                const hostIds = scheduledMaintenance.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 &&
                ((_c = scheduledMaintenance.kubernetesClusters) === null || _c === void 0 ? void 0 : _c.length)) {
                const clusterIds = scheduledMaintenance.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 && ((_d = scheduledMaintenance.dockerHosts) === null || _d === void 0 ? void 0 : _d.length)) {
                const dockerHostIds = scheduledMaintenance.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 && ((_e = scheduledMaintenance.services) === null || _e === void 0 ? void 0 : _e.length)) {
                const serviceIds = scheduledMaintenance.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 ScheduledMaintenanceService.addOwners(scheduledMaintenance.projectId, scheduledMaintenance.id, userIds, teamIds, notify, { isRoot: true });
            }
            logger.debug(`ScheduledMaintenanceOwnerRuleEngine added owners to event ${scheduledMaintenance.id}`, {
                projectId: scheduledMaintenance.projectId.toString(),
            });
            await this.createRuleExecutedFeedItem({
                scheduledMaintenance,
                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 scheduled maintenance owner rules: ${error}`, {
                projectId: (_f = scheduledMaintenance.projectId) === null || _f === void 0 ? void 0 : _f.toString(),
                scheduledMaintenanceId: (_g = scheduledMaintenance.id) === null || _g === void 0 ? void 0 : _g.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { scheduledMaintenance, matchedRules, userIds, teamIds, inheritedFromMonitors, inheritedFromHosts, inheritedFromKubernetesClusters, inheritedFromDockerHosts, inheritedFromServices, } = data;
        if (!scheduledMaintenance.id ||
            !scheduledMaintenance.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("monitors");
            }
            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 event's ${inheritedSources.join(", ")}._`
                : "";
            const feedInfoInMarkdown = `🛡️ **Scheduled Maintenance Owner Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAssigned the following owner${userLines.length + teamLines.length === 1 ? "" : "s"} to the event:${ownersPart}${inheritedNote}`;
            await ScheduledMaintenanceFeedService.createScheduledMaintenanceFeedItem({
                scheduledMaintenanceId: scheduledMaintenance.id,
                projectId: scheduledMaintenance.projectId,
                scheduledMaintenanceFeedEventType: ScheduledMaintenanceFeedEventType.OwnerRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`ScheduledMaintenanceOwnerRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = scheduledMaintenance.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                scheduledMaintenanceId: (_b = scheduledMaintenance.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesScheduledMaintenanceMatchRule(scheduledMaintenance, rule) {
        if (rule.monitors && rule.monitors.length > 0) {
            if (!scheduledMaintenance.monitors ||
                scheduledMaintenance.monitors.length === 0) {
                return false;
            }
            const ruleMonitorIds = rule.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const eventMonitorIds = scheduledMaintenance.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleMonitorIds.some((id) => {
                return eventMonitorIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.scheduledMaintenanceLabels &&
            rule.scheduledMaintenanceLabels.length > 0) {
            if (!scheduledMaintenance.labels ||
                scheduledMaintenance.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.scheduledMaintenanceLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const eventLabelIds = scheduledMaintenance.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return eventLabelIds.includes(id);
            })) {
                return false;
            }
        }
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!scheduledMaintenance.monitors ||
                scheduledMaintenance.monitors.length === 0) {
                return false;
            }
            let anyMonitorMatches = false;
            for (const eventMonitor of scheduledMaintenance.monitors) {
                if (!eventMonitor.id) {
                    continue;
                }
                const monitor = await MonitorService.findOneById({
                    id: eventMonitor.id,
                    select: {
                        name: true,
                        description: true,
                        labels: { _id: true },
                    },
                    props: { isRoot: true },
                });
                if (!monitor) {
                    continue;
                }
                let monitorMatches = true;
                if (rule.monitorLabels && rule.monitorLabels.length > 0) {
                    if (!monitor.labels || monitor.labels.length === 0) {
                        monitorMatches = false;
                    }
                    else {
                        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);
                        })) {
                            monitorMatches = false;
                        }
                    }
                }
                if (monitorMatches &&
                    rule.monitorNamePattern &&
                    (!monitor.name ||
                        !this.testRegex(rule.monitorNamePattern, monitor.name, rule))) {
                    monitorMatches = false;
                }
                if (monitorMatches &&
                    rule.monitorDescriptionPattern &&
                    (!monitor.description ||
                        !this.testRegex(rule.monitorDescriptionPattern, monitor.description, rule))) {
                    monitorMatches = false;
                }
                if (monitorMatches) {
                    anyMonitorMatches = true;
                    break;
                }
            }
            if (!anyMonitorMatches) {
                return false;
            }
        }
        if (rule.titlePattern &&
            (!scheduledMaintenance.title ||
                !this.testRegex(rule.titlePattern, scheduledMaintenance.title, rule))) {
            return false;
        }
        if (rule.descriptionPattern &&
            (!scheduledMaintenance.description ||
                !this.testRegex(rule.descriptionPattern, scheduledMaintenance.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 scheduled maintenance owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ScheduledMaintenance]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceOwnerRuleEngineServiceClass.prototype, "applyRulesToScheduledMaintenance", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceOwnerRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ScheduledMaintenance,
        ScheduledMaintenanceOwnerRule]),
    __metadata("design:returntype", Promise)
], ScheduledMaintenanceOwnerRuleEngineServiceClass.prototype, "doesScheduledMaintenanceMatchRule", null);
export default new ScheduledMaintenanceOwnerRuleEngineServiceClass();
//# sourceMappingURL=ScheduledMaintenanceOwnerRuleEngineService.js.map