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 AlertOnCallRule from "../../Models/DatabaseModels/AlertOnCallRule";
import AlertFeedService from "./AlertFeedService";
import AlertOnCallRuleService from "./AlertOnCallRuleService";
import AlertService from "./AlertService";
import MonitorService from "./MonitorService";
import OnCallDutyPolicyService from "./OnCallDutyPolicyService";
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 AlertOnCallRuleEngineServiceClass {
    /**
     * Evaluates AlertOnCallRule rows for the given alert and merges any
     * matching rules' on-call policies into the alert's onCallDutyPolicies
     * array (deduped). The caller's existing on-call fan-out then runs the
     * merged list, so each policy executes at most once per alert.
     */
    async applyRulesToAlert(alert) {
        var _a, _b, _c;
        if (!alert.id || !alert.projectId) {
            return;
        }
        try {
            const rules = await AlertOnCallRuleService.findBy({
                query: {
                    projectId: alert.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitors: { _id: true },
                    alertSeverities: { _id: true },
                    alertLabels: { _id: true },
                    monitorLabels: { _id: true },
                    alertTitlePattern: true,
                    alertDescriptionPattern: true,
                    monitorNamePattern: true,
                    monitorDescriptionPattern: true,
                    onCallDutyPolicies: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const matchedPolicies = new Map();
            const matchedRules = [];
            for (const rule of rules) {
                const matches = await this.doesAlertMatchRule(alert, rule);
                if (!matches) {
                    continue;
                }
                if (rule.onCallDutyPolicies && rule.onCallDutyPolicies.length > 0) {
                    let ruleAddedAny = false;
                    for (const policy of rule.onCallDutyPolicies) {
                        const policyId = (_a = policy.id) === null || _a === void 0 ? void 0 : _a.toString();
                        if (policyId && !matchedPolicies.has(policyId)) {
                            matchedPolicies.set(policyId, policy);
                            ruleAddedAny = true;
                        }
                    }
                    if (ruleAddedAny) {
                        matchedRules.push(rule);
                    }
                }
            }
            if (matchedPolicies.size === 0) {
                return;
            }
            const existingIds = new Set((alert.onCallDutyPolicies || [])
                .map((p) => {
                var _a;
                return ((_a = p.id) === null || _a === void 0 ? void 0 : _a.toString()) || p._id || "";
            })
                .filter((id) => {
                return id !== "";
            }));
            const merged = [
                ...(alert.onCallDutyPolicies || []),
            ];
            const toAddIds = [];
            for (const [policyId, policy] of matchedPolicies) {
                if (!existingIds.has(policyId)) {
                    merged.push(policy);
                    toAddIds.push(policyId);
                }
            }
            /*
             * Update in-memory list so the existing on-call fan-out runs the merged
             * set in the next .then() step of onCreateSuccess.
             */
            alert.onCallDutyPolicies = merged;
            /*
             * Persist the new join rows so the alert detail UI shows the
             * rule-attached policies alongside any manually-attached ones.
             */
            if (toAddIds.length > 0) {
                try {
                    await AlertService.getRepository()
                        .createQueryBuilder()
                        .relation(Alert, "onCallDutyPolicies")
                        .of(alert.id.toString())
                        .add(toAddIds);
                }
                catch (err) {
                    logger.warn(`AlertOnCallRuleEngine: failed to persist join rows for alert ${alert.id}: ${err instanceof Error ? err.message : String(err)}`);
                }
            }
            logger.debug(`AlertOnCallRuleEngine merged ${matchedPolicies.size} matched policies into alert ${alert.id}`, { projectId: alert.projectId.toString() });
            if (toAddIds.length > 0) {
                await this.createRuleExecutedFeedItem({
                    alert,
                    matchedRules,
                    addedPolicyIds: toAddIds,
                });
            }
        }
        catch (error) {
            logger.error(`Error applying alert on-call rules: ${error}`, {
                projectId: (_b = alert.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                alertId: (_c = alert.id) === null || _c === void 0 ? void 0 : _c.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { alert, matchedRules, addedPolicyIds } = data;
        if (!alert.id ||
            !alert.projectId ||
            matchedRules.length === 0 ||
            addedPolicyIds.length === 0) {
            return;
        }
        try {
            const policyObjectIds = addedPolicyIds.map((id) => {
                return new ObjectID(id);
            });
            const policies = await OnCallDutyPolicyService.findBy({
                query: {
                    _id: QueryHelper.any(policyObjectIds),
                },
                select: { name: true },
                props: { isRoot: true },
                limit: LIMIT_MAX,
                skip: 0,
            });
            const policyNames = policies
                .map((p) => {
                var _a;
                return ((_a = p.name) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            })
                .filter((n) => {
                return n !== "";
            });
            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 policiesPart = policyNames.length > 0
                ? policyNames
                    .map((n) => {
                    return `\n- ${n}`;
                })
                    .join("")
                : "\n- (no named policies)";
            const feedInfoInMarkdown = `📞 **Alert On-Call Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAttached the following on-call ${policyNames.length === 1 ? "policy" : "policies"} to the alert:${policiesPart}`;
            await AlertFeedService.createAlertFeedItem({
                alertId: alert.id,
                projectId: alert.projectId,
                alertFeedEventType: AlertFeedEventType.OnCallRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertOnCallRuleEngine: 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) {
        // Monitors: alert must come from one of the rule's monitors
        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;
            }
        }
        // Severity
        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;
            }
        }
        // Alert labels
        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()) || "";
            });
            const hasMatch = ruleLabelIds.some((id) => {
                return alertLabelIds.includes(id);
            });
            if (!hasMatch) {
                return false;
            }
        }
        // Monitor-derived criteria
        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()) || "";
                });
                const hasMatch = ruleMonitorLabelIds.some((id) => {
                    return monitorLabelIds.includes(id);
                });
                if (!hasMatch) {
                    return false;
                }
            }
            if (rule.monitorNamePattern) {
                if (!monitor.name ||
                    !this.testRegex(rule.monitorNamePattern, monitor.name, rule)) {
                    return false;
                }
            }
            if (rule.monitorDescriptionPattern) {
                if (!monitor.description ||
                    !this.testRegex(rule.monitorDescriptionPattern, monitor.description, rule)) {
                    return false;
                }
            }
        }
        if (rule.alertTitlePattern) {
            if (!alert.title ||
                !this.testRegex(rule.alertTitlePattern, alert.title, rule)) {
                return false;
            }
        }
        if (rule.alertDescriptionPattern) {
            if (!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 pattern in alert on-call rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert]),
    __metadata("design:returntype", Promise)
], AlertOnCallRuleEngineServiceClass.prototype, "applyRulesToAlert", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertOnCallRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert,
        AlertOnCallRule]),
    __metadata("design:returntype", Promise)
], AlertOnCallRuleEngineServiceClass.prototype, "doesAlertMatchRule", null);
export default new AlertOnCallRuleEngineServiceClass();
//# sourceMappingURL=AlertOnCallRuleEngineService.js.map