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 Incident from "../../Models/DatabaseModels/Incident";
import IncidentOnCallRule from "../../Models/DatabaseModels/IncidentOnCallRule";
import IncidentFeedService from "./IncidentFeedService";
import IncidentOnCallRuleService from "./IncidentOnCallRuleService";
import IncidentService from "./IncidentService";
import MonitorService from "./MonitorService";
import OnCallDutyPolicyService from "./OnCallDutyPolicyService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
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 IncidentOnCallRuleEngineServiceClass {
    /**
     * Evaluates IncidentOnCallRule rows for the given incident and merges any
     * matching rules' on-call policies into the incident'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 incident.
     */
    async applyRulesToIncident(incident) {
        var _a, _b, _c;
        if (!incident.id || !incident.projectId) {
            return;
        }
        try {
            const rules = await IncidentOnCallRuleService.findBy({
                query: {
                    projectId: incident.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    monitors: { _id: true },
                    incidentSeverities: { _id: true },
                    incidentLabels: { _id: true },
                    monitorLabels: { _id: true },
                    incidentTitlePattern: true,
                    incidentDescriptionPattern: 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.doesIncidentMatchRule(incident, 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((incident.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 = [
                ...(incident.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.
             */
            incident.onCallDutyPolicies = merged;
            /*
             * Persist the new join rows so the incident detail UI shows the
             * rule-attached policies alongside any manually-attached ones.
             */
            if (toAddIds.length > 0) {
                try {
                    await IncidentService.getRepository()
                        .createQueryBuilder()
                        .relation(Incident, "onCallDutyPolicies")
                        .of(incident.id.toString())
                        .add(toAddIds);
                }
                catch (err) {
                    logger.warn(`IncidentOnCallRuleEngine: failed to persist join rows for incident ${incident.id}: ${err instanceof Error ? err.message : String(err)}`);
                }
            }
            logger.debug(`IncidentOnCallRuleEngine merged ${matchedPolicies.size} matched policies into incident ${incident.id}`, { projectId: incident.projectId.toString() });
            if (toAddIds.length > 0) {
                await this.createRuleExecutedFeedItem({
                    incident,
                    matchedRules,
                    addedPolicyIds: toAddIds,
                });
            }
        }
        catch (error) {
            logger.error(`Error applying incident on-call rules: ${error}`, {
                projectId: (_b = incident.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                incidentId: (_c = incident.id) === null || _c === void 0 ? void 0 : _c.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { incident, matchedRules, addedPolicyIds } = data;
        if (!incident.id ||
            !incident.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 = `📞 **Incident On-Call Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAttached the following on-call ${policyNames.length === 1 ? "policy" : "policies"} to the incident:${policiesPart}`;
            await IncidentFeedService.createIncidentFeedItem({
                incidentId: incident.id,
                projectId: incident.projectId,
                incidentFeedEventType: IncidentFeedEventType.OnCallRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`IncidentOnCallRuleEngine: failed to create rule-executed feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = incident.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                incidentId: (_b = incident.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    async doesIncidentMatchRule(incident, rule) {
        // Monitors: incident must come from at least one of the rule's monitors
        if (rule.monitors && rule.monitors.length > 0) {
            if (!incident.monitors || incident.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 incidentMonitorIds = incident.monitors.map((m) => {
                var _a;
                return ((_a = m.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const hasMatch = ruleMonitorIds.some((id) => {
                return incidentMonitorIds.includes(id);
            });
            if (!hasMatch) {
                return false;
            }
        }
        // Severity
        if (rule.incidentSeverities && rule.incidentSeverities.length > 0) {
            if (!incident.incidentSeverityId) {
                return false;
            }
            const severityIds = rule.incidentSeverities.map((s) => {
                var _a;
                return ((_a = s.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!severityIds.includes(incident.incidentSeverityId.toString())) {
                return false;
            }
        }
        // Incident labels
        if (rule.incidentLabels && rule.incidentLabels.length > 0) {
            if (!incident.labels || incident.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.incidentLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const incidentLabelIds = incident.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const hasMatch = ruleLabelIds.some((id) => {
                return incidentLabelIds.includes(id);
            });
            if (!hasMatch) {
                return false;
            }
        }
        // Monitor-derived criteria (labels, name, description)
        const hasMonitorCriteria = Boolean((rule.monitorLabels && rule.monitorLabels.length > 0) ||
            rule.monitorNamePattern ||
            rule.monitorDescriptionPattern);
        if (hasMonitorCriteria) {
            if (!incident.monitors || incident.monitors.length === 0) {
                return false;
            }
            let anyMonitorMatches = false;
            for (const incidentMonitor of incident.monitors) {
                if (!incidentMonitor.id) {
                    continue;
                }
                const monitor = await MonitorService.findOneById({
                    id: incidentMonitor.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()) || "";
                        });
                        const hasMatch = ruleMonitorLabelIds.some((id) => {
                            return monitorLabelIds.includes(id);
                        });
                        if (!hasMatch) {
                            monitorMatches = false;
                        }
                    }
                }
                if (monitorMatches && rule.monitorNamePattern) {
                    if (!monitor.name ||
                        !this.testRegex(rule.monitorNamePattern, monitor.name, rule)) {
                        monitorMatches = false;
                    }
                }
                if (monitorMatches && rule.monitorDescriptionPattern) {
                    if (!monitor.description ||
                        !this.testRegex(rule.monitorDescriptionPattern, monitor.description, rule)) {
                        monitorMatches = false;
                    }
                }
                if (monitorMatches) {
                    anyMonitorMatches = true;
                    break;
                }
            }
            if (!anyMonitorMatches) {
                return false;
            }
        }
        if (rule.incidentTitlePattern) {
            if (!incident.title ||
                !this.testRegex(rule.incidentTitlePattern, incident.title, rule)) {
                return false;
            }
        }
        if (rule.incidentDescriptionPattern) {
            if (!incident.description ||
                !this.testRegex(rule.incidentDescriptionPattern, incident.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 incident on-call rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident]),
    __metadata("design:returntype", Promise)
], IncidentOnCallRuleEngineServiceClass.prototype, "applyRulesToIncident", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncidentOnCallRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident,
        IncidentOnCallRule]),
    __metadata("design:returntype", Promise)
], IncidentOnCallRuleEngineServiceClass.prototype, "doesIncidentMatchRule", null);
export default new IncidentOnCallRuleEngineServiceClass();
//# sourceMappingURL=IncidentOnCallRuleEngineService.js.map