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 IncidentPrivacyRule from "../../Models/DatabaseModels/IncidentPrivacyRule";
import IncidentFeedService from "./IncidentFeedService";
import IncidentPrivacyRuleService from "./IncidentPrivacyRuleService";
import IncidentService from "./IncidentService";
import MonitorService from "./MonitorService";
import { IncidentFeedEventType } from "../../Models/DatabaseModels/IncidentFeed";
import { Red500 } from "../../Types/BrandColors";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class IncidentPrivacyRuleEngineServiceClass {
    /**
     * Evaluates IncidentPrivacyRule rows for the given incident. If any enabled
     * rule matches, the incident is marked private (isPrivate=true) and the
     * passed-in incident object is mutated in place so downstream callers see
     * the updated value.
     *
     * Returns true if the incident was marked private by a rule.
     */
    async applyRulesToIncident(incident) {
        var _a, _b;
        if (!incident.id || !incident.projectId) {
            return false;
        }
        if (incident.isPrivate === true) {
            // Already private — nothing to do.
            return false;
        }
        try {
            const rules = await IncidentPrivacyRuleService.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,
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return false;
            }
            const matchedRules = [];
            for (const rule of rules) {
                const matches = await this.doesIncidentMatchRule(incident, rule);
                if (matches) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return false;
            }
            await IncidentService.updateOneById({
                id: incident.id,
                data: { isPrivate: true },
                props: { isRoot: true },
            });
            // Mirror in memory so downstream onCreateSuccess steps see the change.
            incident.isPrivate = true;
            logger.debug(`IncidentPrivacyRuleEngine marked incident ${incident.id} private`, { projectId: incident.projectId.toString() });
            await this.createRuleExecutedFeedItem({ incident, matchedRules });
            return true;
        }
        catch (error) {
            logger.error(`Error applying incident privacy rules: ${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(),
            });
            return false;
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { incident, matchedRules } = data;
        if (!incident.id || !incident.projectId || matchedRules.length === 0) {
            return;
        }
        try {
            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 feedInfoInMarkdown = `🔒 **Incident Privacy Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nIncident has been marked **private** — visible only to its owners, project admins, and project owners.`;
            await IncidentFeedService.createIncidentFeedItem({
                incidentId: incident.id,
                projectId: incident.projectId,
                incidentFeedEventType: IncidentFeedEventType.PrivacyRuleExecuted,
                displayColor: Red500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`IncidentPrivacyRuleEngine: 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) {
        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()) || "";
            });
            if (!ruleMonitorIds.some((id) => {
                return incidentMonitorIds.includes(id);
            })) {
                return false;
            }
        }
        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;
            }
        }
        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()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return incidentLabelIds.includes(id);
            })) {
                return false;
            }
        }
        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()) || "";
                        });
                        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.incidentTitlePattern &&
            (!incident.title ||
                !this.testRegex(rule.incidentTitlePattern, incident.title, rule))) {
            return false;
        }
        if (rule.incidentDescriptionPattern &&
            (!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 in incident privacy rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident]),
    __metadata("design:returntype", Promise)
], IncidentPrivacyRuleEngineServiceClass.prototype, "applyRulesToIncident", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncidentPrivacyRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Incident,
        IncidentPrivacyRule]),
    __metadata("design:returntype", Promise)
], IncidentPrivacyRuleEngineServiceClass.prototype, "doesIncidentMatchRule", null);
export default new IncidentPrivacyRuleEngineServiceClass();
//# sourceMappingURL=IncidentPrivacyRuleEngineService.js.map