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 Label from "../../Models/DatabaseModels/Label";
import Runbook from "../../Models/DatabaseModels/Runbook";
import RunbookLabelRuleService from "./RunbookLabelRuleService";
import RunbookService from "./RunbookService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class RunbookLabelRuleEngineServiceClass {
    /**
     * Evaluates RunbookLabelRule rows for the given runbook and attaches matched
     * labels to it. The union is deduped against labels already on the runbook
     * before insert to avoid PK conflicts on the join table.
     */
    async applyRulesToRunbook(runbook) {
        var _a, _b;
        if (!runbook.id || !runbook.projectId) {
            return;
        }
        try {
            const rules = await RunbookLabelRuleService.findBy({
                query: {
                    projectId: runbook.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    runbookLabels: { _id: true },
                    runbookNamePattern: true,
                    runbookDescriptionPattern: true,
                    labelsToAdd: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const runbookWithDetails = await RunbookService.findOneById({
                id: runbook.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!runbookWithDetails) {
                return;
            }
            const labelIdsToAdd = new Set();
            for (const rule of rules) {
                const matches = this.doesRunbookMatchRule(runbookWithDetails, rule);
                if (!matches) {
                    continue;
                }
                for (const label of rule.labelsToAdd || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
            }
            if (labelIdsToAdd.size === 0) {
                return;
            }
            const existingLabelIds = new Set((runbookWithDetails.labels || [])
                .map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            })
                .filter((id) => {
                return id !== "";
            }));
            const newLabelIds = Array.from(labelIdsToAdd).filter((id) => {
                return !existingLabelIds.has(id);
            });
            if (newLabelIds.length === 0) {
                return;
            }
            await RunbookService.getRepository()
                .createQueryBuilder()
                .relation(Runbook, "labels")
                .of(runbook.id.toString())
                .add(newLabelIds);
            /*
             * Sync in-memory runbook.labels so a downstream owner-rule engine in
             * the same onCreateSuccess chain can match on rule-added labels.
             */
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            runbook.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`RunbookLabelRuleEngine attached ${newLabelIds.length} labels to runbook ${runbook.id}`, { projectId: runbook.projectId.toString() });
        }
        catch (error) {
            logger.error(`Error applying runbook label rules: ${error}`, {
                projectId: (_a = runbook.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                runbookId: (_b = runbook.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesRunbookMatchRule(runbook, rule) {
        if (rule.runbookLabels && rule.runbookLabels.length > 0) {
            if (!runbook.labels || runbook.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.runbookLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const labelIds = runbook.labels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            if (!ruleLabelIds.some((id) => {
                return labelIds.includes(id);
            })) {
                return false;
            }
        }
        if (rule.runbookNamePattern &&
            (!runbook.name ||
                !this.testRegex(rule.runbookNamePattern, runbook.name, rule))) {
            return false;
        }
        if (rule.runbookDescriptionPattern &&
            (!runbook.description ||
                !this.testRegex(rule.runbookDescriptionPattern, runbook.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 runbook label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Runbook]),
    __metadata("design:returntype", Promise)
], RunbookLabelRuleEngineServiceClass.prototype, "applyRulesToRunbook", null);
export default new RunbookLabelRuleEngineServiceClass();
//# sourceMappingURL=RunbookLabelRuleEngineService.js.map