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 AlertPrivacyRule from "../../Models/DatabaseModels/AlertPrivacyRule";
import AlertFeedService from "./AlertFeedService";
import AlertPrivacyRuleService from "./AlertPrivacyRuleService";
import AlertService from "./AlertService";
import MonitorService from "./MonitorService";
import { AlertFeedEventType } from "../../Models/DatabaseModels/AlertFeed";
import { Red500 } from "../../Types/BrandColors";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class AlertPrivacyRuleEngineServiceClass {
    /**
     * Evaluates AlertPrivacyRule rows for the given alert. If any enabled rule
     * matches, the alert is marked private (isPrivate=true) and the passed-in
     * alert object is mutated in place so downstream callers see the update.
     *
     * Returns true if the alert was marked private by a rule.
     */
    async applyRulesToAlert(alert) {
        var _a, _b;
        if (!alert.id || !alert.projectId) {
            return false;
        }
        if (alert.isPrivate === true) {
            // Already private — nothing to do.
            return false;
        }
        try {
            const rules = await AlertPrivacyRuleService.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,
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return false;
            }
            const matchedRules = [];
            for (const rule of rules) {
                const matches = await this.doesAlertMatchRule(alert, rule);
                if (matches) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return false;
            }
            await AlertService.updateOneById({
                id: alert.id,
                data: { isPrivate: true },
                props: { isRoot: true },
            });
            // Mirror in memory so downstream onCreateSuccess steps see the change.
            alert.isPrivate = true;
            logger.debug(`AlertPrivacyRuleEngine marked alert ${alert.id} private`, {
                projectId: alert.projectId.toString(),
            });
            await this.createRuleExecutedFeedItem({ alert, matchedRules });
            return true;
        }
        catch (error) {
            logger.error(`Error applying alert privacy rules: ${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(),
            });
            return false;
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { alert, matchedRules } = data;
        if (!alert.id || !alert.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 = `🔒 **Alert Privacy Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAlert has been marked **private** — visible only to its owners, project admins, and project owners.`;
            await AlertFeedService.createAlertFeedItem({
                alertId: alert.id,
                projectId: alert.projectId,
                alertFeedEventType: AlertFeedEventType.PrivacyRuleExecuted,
                displayColor: Red500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertPrivacyRuleEngine: 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 privacy rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert]),
    __metadata("design:returntype", Promise)
], AlertPrivacyRuleEngineServiceClass.prototype, "applyRulesToAlert", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertPrivacyRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Alert,
        AlertPrivacyRule]),
    __metadata("design:returntype", Promise)
], AlertPrivacyRuleEngineServiceClass.prototype, "doesAlertMatchRule", null);
export default new AlertPrivacyRuleEngineServiceClass();
//# sourceMappingURL=AlertPrivacyRuleEngineService.js.map