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 RumApplication from "../../Models/DatabaseModels/RumApplication";
import RumApplicationLabelRuleService from "./RumApplicationLabelRuleService";
import RumApplicationService from "./RumApplicationService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class RumApplicationLabelRuleEngineServiceClass {
    /**
     * Evaluates RumApplicationLabelRule rows for the given application and
     * attaches matched labels. The union is deduped against labels already on
     * the application before insert to avoid PK conflicts on the join table.
     */
    async applyRulesToRumApplication(rumApplication) {
        var _a, _b;
        if (!rumApplication.id || !rumApplication.projectId) {
            return;
        }
        try {
            const rules = await RumApplicationLabelRuleService.findBy({
                query: {
                    projectId: rumApplication.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    matchLabels: { _id: true },
                    nameRegexPattern: true,
                    descriptionRegexPattern: true,
                    labelsToAdd: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const appWithDetails = await RumApplicationService.findOneById({
                id: rumApplication.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!appWithDetails) {
                return;
            }
            const labelIdsToAdd = new Set();
            for (const rule of rules) {
                if (!this.doesMatchRule(appWithDetails, rule)) {
                    continue;
                }
                for (const label of rule.labelsToAdd || []) {
                    if (label.id) {
                        labelIdsToAdd.add(label.id.toString());
                    }
                }
            }
            if (labelIdsToAdd.size === 0) {
                return;
            }
            const existingLabelIds = new Set((appWithDetails.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 RumApplicationService.getRepository()
                .createQueryBuilder()
                .relation(RumApplication, "labels")
                .of(rumApplication.id.toString())
                .add(newLabelIds);
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            rumApplication.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
        }
        catch (error) {
            logger.error(`Error applying RUM application label rules: ${error}`, {
                projectId: (_a = rumApplication.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                rumApplicationId: (_b = rumApplication.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesMatchRule(rumApplication, rule) {
        if (rule.matchLabels && rule.matchLabels.length > 0) {
            if (!rumApplication.labels || rumApplication.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.matchLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const labelIds = rumApplication.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.nameRegexPattern &&
            (!rumApplication.name ||
                !this.testRegex(rule.nameRegexPattern, rumApplication.name))) {
            return false;
        }
        if (rule.descriptionRegexPattern &&
            (!rumApplication.description ||
                !this.testRegex(rule.descriptionRegexPattern, rumApplication.description))) {
            return false;
        }
        return true;
    }
    testRegex(pattern, value) {
        try {
            const regex = new RegExp(pattern, "i");
            return regex.test(value);
        }
        catch (_a) {
            logger.warn(`Invalid regex in RUM application label rule: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [RumApplication]),
    __metadata("design:returntype", Promise)
], RumApplicationLabelRuleEngineServiceClass.prototype, "applyRulesToRumApplication", null);
export default new RumApplicationLabelRuleEngineServiceClass();
//# sourceMappingURL=RumApplicationLabelRuleEngineService.js.map