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 AlertEpisodeOwnerRuleService from "./AlertEpisodeOwnerRuleService";
import AlertEpisodeService from "./AlertEpisodeService";
import TeamService from "./TeamService";
import UserService from "./UserService";
import { AlertEpisodeFeedEventType } from "../../Models/DatabaseModels/AlertEpisodeFeed";
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 AlertEpisodeOwnerRuleEngineServiceClass {
    /**
     * Evaluates AlertEpisodeOwnerRule rows for the given episode and adds
     * matched owner users / teams via AlertEpisodeService.addOwners. Honors
     * each rule's notifyOwners setting (added owners are notified or silent).
     */
    async applyRulesToEpisode(episode) {
        var _a, _b;
        if (!episode.id || !episode.projectId) {
            return;
        }
        try {
            const rules = await AlertEpisodeOwnerRuleService.findBy({
                query: {
                    projectId: episode.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    alertSeverities: { _id: true },
                    episodeLabels: { _id: true },
                    episodeTitlePattern: true,
                    episodeDescriptionPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const usersByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const teamsByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const matchedRules = [];
            const allUserIds = new Set();
            const allTeamIds = new Set();
            for (const rule of rules) {
                if (!this.doesEpisodeMatchRule(episode, rule)) {
                    continue;
                }
                let ruleAddedAny = false;
                const notify = rule.notifyOwners !== false;
                for (const user of rule.ownerUsers || []) {
                    if (user.id) {
                        usersByNotify.get(notify).add(user.id.toString());
                        allUserIds.add(user.id.toString());
                        ruleAddedAny = true;
                    }
                }
                for (const team of rule.ownerTeams || []) {
                    if (team.id) {
                        teamsByNotify.get(notify).add(team.id.toString());
                        allTeamIds.add(team.id.toString());
                        ruleAddedAny = true;
                    }
                }
                if (ruleAddedAny) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return;
            }
            for (const notify of [true, false]) {
                const userIds = Array.from(usersByNotify.get(notify)).map((id) => {
                    return new ObjectID(id);
                });
                const teamIds = Array.from(teamsByNotify.get(notify)).map((id) => {
                    return new ObjectID(id);
                });
                if (userIds.length === 0 && teamIds.length === 0) {
                    continue;
                }
                await AlertEpisodeService.addOwners(episode.projectId, episode.id, userIds, teamIds, notify, { isRoot: true });
            }
            logger.debug(`AlertEpisodeOwnerRuleEngine added owners to episode ${episode.id}`, { projectId: episode.projectId.toString() });
            await this.createRuleExecutedFeedItem({
                episode,
                matchedRules,
                userIds: Array.from(allUserIds),
                teamIds: Array.from(allTeamIds),
            });
        }
        catch (error) {
            logger.error(`Error applying alert episode owner 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(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { episode, matchedRules, userIds, teamIds } = data;
        if (!episode.id ||
            !episode.projectId ||
            matchedRules.length === 0 ||
            (userIds.length === 0 && teamIds.length === 0)) {
            return;
        }
        try {
            const userObjectIds = userIds.map((id) => {
                return new ObjectID(id);
            });
            const teamObjectIds = teamIds.map((id) => {
                return new ObjectID(id);
            });
            const [users, teams] = await Promise.all([
                userObjectIds.length > 0
                    ? UserService.findBy({
                        query: { _id: QueryHelper.any(userObjectIds) },
                        select: { name: true, email: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    })
                    : Promise.resolve([]),
                teamObjectIds.length > 0
                    ? TeamService.findBy({
                        query: { _id: QueryHelper.any(teamObjectIds) },
                        select: { name: true },
                        props: { isRoot: true },
                        limit: LIMIT_MAX,
                        skip: 0,
                    })
                    : Promise.resolve([]),
            ]);
            const userLines = users.map((u) => {
                var _a, _b;
                const display = ((_a = u.name) === null || _a === void 0 ? void 0 : _a.toString()) || ((_b = u.email) === null || _b === void 0 ? void 0 : _b.toString()) || "Unknown User";
                return `\n- 👤 ${display}`;
            });
            const teamLines = teams.map((t) => {
                var _a;
                return `\n- 👥 ${((_a = t.name) === null || _a === void 0 ? void 0 : _a.toString()) || "Unnamed Team"}`;
            });
            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 ownersPart = userLines.length + teamLines.length > 0
                ? userLines.concat(teamLines).join("")
                : "\n- (no named owners)";
            const feedInfoInMarkdown = `🛡️ **Alert Episode Owner Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAssigned the following owner${userLines.length + teamLines.length === 1 ? "" : "s"} to the episode:${ownersPart}`;
            await AlertEpisodeFeedService.createAlertEpisodeFeedItem({
                alertEpisodeId: episode.id,
                projectId: episode.projectId,
                alertEpisodeFeedEventType: AlertEpisodeFeedEventType.OwnerRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`AlertEpisodeOwnerRuleEngine: failed to create rule-executed 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 owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [AlertEpisode]),
    __metadata("design:returntype", Promise)
], AlertEpisodeOwnerRuleEngineServiceClass.prototype, "applyRulesToEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], AlertEpisodeOwnerRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new AlertEpisodeOwnerRuleEngineServiceClass();
//# sourceMappingURL=AlertEpisodeOwnerRuleEngineService.js.map