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 IncomingCallPolicy from "../../Models/DatabaseModels/IncomingCallPolicy";
import IncomingCallPolicyLabelRuleService from "./IncomingCallPolicyLabelRuleService";
import IncomingCallPolicyService from "./IncomingCallPolicyService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class IncomingCallPolicyLabelRuleEngineServiceClass {
    async applyRulesToIncomingCallPolicy(policy) {
        var _a, _b;
        if (!policy.id || !policy.projectId) {
            return;
        }
        try {
            const rules = await IncomingCallPolicyLabelRuleService.findBy({
                query: {
                    projectId: policy.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    incomingCallPolicyLabels: { _id: true },
                    incomingCallPolicyNamePattern: true,
                    incomingCallPolicyDescriptionPattern: true,
                    labelsToAdd: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const policyWithDetails = await IncomingCallPolicyService.findOneById({
                id: policy.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!policyWithDetails) {
                return;
            }
            const labelIdsToAdd = new Set();
            for (const rule of rules) {
                const matches = this.doesPolicyMatchRule(policyWithDetails, 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((policyWithDetails.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 IncomingCallPolicyService.getRepository()
                .createQueryBuilder()
                .relation(IncomingCallPolicy, "labels")
                .of(policy.id.toString())
                .add(newLabelIds);
            const mergedLabelIds = new Set([
                ...existingLabelIds,
                ...newLabelIds,
            ]);
            policy.labels = Array.from(mergedLabelIds).map((id) => {
                const label = new Label();
                label.id = new ObjectID(id);
                return label;
            });
            logger.debug(`IncomingCallPolicyLabelRuleEngine attached ${newLabelIds.length} labels to policy ${policy.id}`, { projectId: policy.projectId.toString() });
        }
        catch (error) {
            logger.error(`Error applying incoming call policy label rules: ${error}`, {
                projectId: (_a = policy.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                incomingCallPolicyId: (_b = policy.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesPolicyMatchRule(policy, rule) {
        if (rule.incomingCallPolicyLabels &&
            rule.incomingCallPolicyLabels.length > 0) {
            if (!policy.labels || policy.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.incomingCallPolicyLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const labelIds = policy.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.incomingCallPolicyNamePattern &&
            (!policy.name ||
                !this.testRegex(rule.incomingCallPolicyNamePattern, policy.name, rule))) {
            return false;
        }
        if (rule.incomingCallPolicyDescriptionPattern &&
            (!policy.description ||
                !this.testRegex(rule.incomingCallPolicyDescriptionPattern, policy.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 incoming call policy label rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [IncomingCallPolicy]),
    __metadata("design:returntype", Promise)
], IncomingCallPolicyLabelRuleEngineServiceClass.prototype, "applyRulesToIncomingCallPolicy", null);
export default new IncomingCallPolicyLabelRuleEngineServiceClass();
//# sourceMappingURL=IncomingCallPolicyLabelRuleEngineService.js.map