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 AlertEpisode from "../../Models/DatabaseModels/AlertEpisode";
import AlertEpisodeFeedService from "./AlertEpisodeFeedService";
import AlertEpisodePrivacyRuleService from "./AlertEpisodePrivacyRuleService";
import AlertEpisodeService from "./AlertEpisodeService";
import { AlertEpisodeFeedEventType } from "../../Models/DatabaseModels/AlertEpisodeFeed";
import { Red500 } from "../../Types/BrandColors";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class AlertEpisodePrivacyRuleEngineServiceClass {
    /**
     * Evaluates AlertEpisodePrivacyRule rows for the given episode. If any
     * enabled rule matches, the episode is marked private (isPrivate=true).
     */
    async applyRulesToEpisode(episode) {
        var _a, _b;
        if (!episode.id || !episode.projectId) {
            return false;
        }
        if (episode.isPrivate === true) {
            return false;
        }
        try {
            const rules = await AlertEpisodePrivacyRuleService.findBy({
                query: {
                    projectId: episode.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    alertSeverities: { _id: true },
                    episodeLabels: { _id: true },
                    episodeTitlePattern: true,
                    episodeDescriptionPattern: true,
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return false;
            }
            const matchedRules = [];
            for (const rule of rules) {
                if (this.doesEpisodeMatchRule(episode, rule)) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return false;
            }
            await AlertEpisodeService.updateOneById({
                id: episode.id,
                data: { isPrivate: true },
                props: { isRoot: true },
            });
            episode.isPrivate = true;
            logger.debug(`AlertEpisodePrivacyRuleEngine marked episode ${episode.id} private`, { projectId: episode.projectId.toString() });
            await this.createRuleExecutedFeedItem({ episode, matchedRules });
            return true;
        }
        catch (error) {
            logger.error(`Error applying alert episode privacy rules: ${error}`, {
                projectId: (_a = episode.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                alertEpisodeId: (_b = episode.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
            return false;
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { episode, matchedRules } = data;
        if (!episode.id || !episode.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 Episode Privacy Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nEpisode has been marked **private** — visible only to its owners, project admins, and project owners.`;
            await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
                alertEpisodeId: episode.id,
                projectId: episode.projectId,
                alertEpisodeFeedEventType: AlertEpisodeFeedEventType.PrivacyRuleExecuted,
                displayColor: Red500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertEpisodePrivacyRuleEngine: failed to create feed item: ${error instanceof Error ? error.message : String(error)}`, {
                projectId: (_a = episode.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                alertEpisodeId: (_b = episode.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesEpisodeMatchRule(episode, rule) {
        if (rule.alertSeverities && rule.alertSeverities.length > 0) {
            if (!episode.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(episode.alertSeverityId.toString())) {
                return false;
            }
        }
        if (rule.episodeLabels && rule.episodeLabels.length > 0) {
            if (!episode.labels || episode.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.episodeLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const episodeLabelIds = episode.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return episodeLabelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.episodeTitlePattern &&
            (!episode.title ||
                !this.testRegex(rule.episodeTitlePattern, episode.title, rule))) {
            return false;
        }
        if (rule.episodeDescriptionPattern &&
            (!episode.description ||
                !this.testRegex(rule.episodeDescriptionPattern, episode.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 episode privacy rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [AlertEpisode]),
    __metadata("design:returntype", Promise)
], AlertEpisodePrivacyRuleEngineServiceClass.prototype, "applyRulesToEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertEpisodePrivacyRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new AlertEpisodePrivacyRuleEngineServiceClass();
//# sourceMappingURL=AlertEpisodePrivacyRuleEngineService.js.map