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 IncidentEpisode from "../../Models/DatabaseModels/IncidentEpisode";
import IncidentEpisodeFeedService from "./IncidentEpisodeFeedService";
import IncidentEpisodeOnCallRuleService from "./IncidentEpisodeOnCallRuleService";
import IncidentEpisodeService from "./IncidentEpisodeService";
import OnCallDutyPolicyService from "./OnCallDutyPolicyService";
import { IncidentEpisodeFeedEventType } from "../../Models/DatabaseModels/IncidentEpisodeFeed";
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 IncidentEpisodeOnCallRuleEngineServiceClass {
    /**
     * Evaluates IncidentEpisodeOnCallRule rows for the given episode and merges
     * matched rules' on-call policies into the episode's onCallDutyPolicies
     * array (deduped). The episode service's existing on-call fan-out then runs
     * the merged list, so each policy executes at most once per episode.
     */
    async applyRulesToEpisode(episode) {
        var _a, _b, _c;
        if (!episode.id || !episode.projectId) {
            return;
        }
        try {
            const rules = await IncidentEpisodeOnCallRuleService.findBy({
                query: {
                    projectId: episode.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    incidentSeverities: { _id: true },
                    episodeLabels: { _id: true },
                    episodeTitlePattern: true,
                    episodeDescriptionPattern: true,
                    onCallDutyPolicies: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const matchedPolicies = new Map();
            const matchedRules = [];
            for (const rule of rules) {
                if (!this.doesEpisodeMatchRule(episode, rule)) {
                    continue;
                }
                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((episode.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 = [
                ...(episode.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 fan-out runs the merged set.
            episode.onCallDutyPolicies = merged;
            // Persist new join rows so the episode detail UI shows them.
            if (toAddIds.length > 0) {
                try {
                    await IncidentEpisodeService.getRepository()
                        .createQueryBuilder()
                        .relation(IncidentEpisode, "onCallDutyPolicies")
                        .of(episode.id.toString())
                        .add(toAddIds);
                }
                catch (err) {
                    logger.warn(`IncidentEpisodeOnCallRuleEngine: failed to persist join rows for episode ${episode.id}: ${err instanceof Error ? err.message : String(err)}`);
                }
            }
            logger.debug(`IncidentEpisodeOnCallRuleEngine merged ${matchedPolicies.size} matched policies into episode ${episode.id}`, { projectId: episode.projectId.toString() });
            if (toAddIds.length > 0) {
                await this.createRuleExecutedFeedItem({
                    episode,
                    matchedRules,
                    addedPolicyIds: toAddIds,
                });
            }
        }
        catch (error) {
            logger.error(`Error applying incident episode on-call rules: ${error}`, {
                projectId: (_b = episode.projectId) === null || _b === void 0 ? void 0 : _b.toString(),
                incidentEpisodeId: (_c = episode.id) === null || _c === void 0 ? void 0 : _c.toString(),
            });
        }
    }
    async createRuleExecutedFeedItem(data) {
        var _a, _b;
        const { episode, matchedRules, addedPolicyIds } = data;
        if (!episode.id ||
            !episode.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 Episode On-Call Rule${matchedRules.length > 1 ? "s" : ""} executed:** ${rulesPart}\n\nAttached the following on-call ${policyNames.length === 1 ? "policy" : "policies"} to the episode:${policiesPart}`;
            await IncidentEpisodeFeedService.createIncidentEpisodeFeedItem({
                incidentEpisodeId: episode.id,
                projectId: episode.projectId,
                incidentEpisodeFeedEventType: IncidentEpisodeFeedEventType.OnCallRuleExecuted,
                displayColor: Indigo500,
                feedInfoInMarkdown,
            });
        }
        catch (error) {
            logger.error(`IncidentEpisodeOnCallRuleEngine: 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(),
                incidentEpisodeId: (_b = episode.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesEpisodeMatchRule(episode, rule) {
        if (rule.incidentSeverities && rule.incidentSeverities.length > 0) {
            if (!episode.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(episode.incidentSeverityId.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 incident episode on-call rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [IncidentEpisode]),
    __metadata("design:returntype", Promise)
], IncidentEpisodeOnCallRuleEngineServiceClass.prototype, "applyRulesToEpisode", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncidentEpisodeOnCallRuleEngineServiceClass.prototype, "createRuleExecutedFeedItem", null);
export default new IncidentEpisodeOnCallRuleEngineServiceClass();
//# sourceMappingURL=IncidentEpisodeOnCallRuleEngineService.js.map