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 Dashboard from "../../Models/DatabaseModels/Dashboard";
import DashboardOwnerTeam from "../../Models/DatabaseModels/DashboardOwnerTeam";
import DashboardOwnerUser from "../../Models/DatabaseModels/DashboardOwnerUser";
import DashboardOwnerRuleService from "./DashboardOwnerRuleService";
import DashboardOwnerTeamService from "./DashboardOwnerTeamService";
import DashboardOwnerUserService from "./DashboardOwnerUserService";
import DashboardService from "./DashboardService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class DashboardOwnerRuleEngineServiceClass {
    /**
     * Evaluates DashboardOwnerRule rows for the given dashboard and adds matched
     * owner users / teams via DashboardOwnerUserService / DashboardOwnerTeamService.
     * Rules with notifyOwners set notify the added owners; rules with notifyOwners
     * off add silently.
     */
    async applyRulesToDashboard(dashboard) {
        var _a, _b;
        if (!dashboard.id || !dashboard.projectId) {
            return;
        }
        try {
            const rules = await DashboardOwnerRuleService.findBy({
                query: {
                    projectId: dashboard.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    dashboardLabels: { _id: true },
                    dashboardNamePattern: true,
                    dashboardDescriptionPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const dashboardWithDetails = await DashboardService.findOneById({
                id: dashboard.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!dashboardWithDetails) {
                return;
            }
            const usersByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const teamsByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const matchedRules = [];
            for (const rule of rules) {
                const matches = this.doesDashboardMatchRule(dashboardWithDetails, rule);
                if (!matches) {
                    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());
                        ruleAddedAny = true;
                    }
                }
                for (const team of rule.ownerTeams || []) {
                    if (team.id) {
                        teamsByNotify.get(notify).add(team.id.toString());
                        ruleAddedAny = true;
                    }
                }
                if (ruleAddedAny) {
                    matchedRules.push(rule);
                }
            }
            if (matchedRules.length === 0) {
                return;
            }
            for (const notify of [true, false]) {
                const userIds = usersByNotify.get(notify);
                const teamIds = teamsByNotify.get(notify);
                for (const userId of userIds) {
                    const owner = new DashboardOwnerUser();
                    owner.dashboardId = dashboard.id;
                    owner.projectId = dashboard.projectId;
                    owner.userId = new ObjectID(userId);
                    owner.isOwnerNotified = !notify;
                    await DashboardOwnerUserService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
                for (const teamId of teamIds) {
                    const owner = new DashboardOwnerTeam();
                    owner.dashboardId = dashboard.id;
                    owner.projectId = dashboard.projectId;
                    owner.teamId = new ObjectID(teamId);
                    owner.isOwnerNotified = !notify;
                    await DashboardOwnerTeamService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
            }
            logger.debug(`DashboardOwnerRuleEngine added owners to dashboard ${dashboard.id}`, { projectId: dashboard.projectId.toString() });
        }
        catch (error) {
            logger.error(`Error applying dashboard owner rules: ${error}`, {
                projectId: (_a = dashboard.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                dashboardId: (_b = dashboard.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesDashboardMatchRule(dashboard, rule) {
        if (rule.dashboardLabels && rule.dashboardLabels.length > 0) {
            if (!dashboard.labels || dashboard.labels.length === 0) {
                return false;
            }
            const ruleLabelIds = rule.dashboardLabels.map((l) => {
                var _a;
                return ((_a = l.id) === null || _a === void 0 ? void 0 : _a.toString()) || "";
            });
            const labelIds = dashboard.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.dashboardNamePattern &&
            (!dashboard.name ||
                !this.testRegex(rule.dashboardNamePattern, dashboard.name, rule))) {
            return false;
        }
        if (rule.dashboardDescriptionPattern &&
            (!dashboard.description ||
                !this.testRegex(rule.dashboardDescriptionPattern, dashboard.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 dashboard owner rule ${rule.id}: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Dashboard]),
    __metadata("design:returntype", Promise)
], DashboardOwnerRuleEngineServiceClass.prototype, "applyRulesToDashboard", null);
export default new DashboardOwnerRuleEngineServiceClass();
//# sourceMappingURL=DashboardOwnerRuleEngineService.js.map