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 ServerlessFunction from "../../Models/DatabaseModels/ServerlessFunction";
import ServerlessFunctionOwnerUser from "../../Models/DatabaseModels/ServerlessFunctionOwnerUser";
import ServerlessFunctionOwnerTeam from "../../Models/DatabaseModels/ServerlessFunctionOwnerTeam";
import ServerlessFunctionOwnerRuleService from "./ServerlessFunctionOwnerRuleService";
import ServerlessFunctionOwnerUserService from "./ServerlessFunctionOwnerUserService";
import ServerlessFunctionOwnerTeamService from "./ServerlessFunctionOwnerTeamService";
import ServerlessFunctionService from "./ServerlessFunctionService";
import ObjectID from "../../Types/ObjectID";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import logger from "../Utils/Logger";
class ServerlessFunctionOwnerRuleEngineServiceClass {
    /**
     * Evaluates ServerlessFunctionOwnerRule rows for the given function and adds
     * matched owner users / teams. Rules with notifyOwners set notify the added
     * owners; rules with notifyOwners off add silently.
     */
    async applyRulesToServerlessFunction(serverlessFunction) {
        var _a, _b;
        if (!serverlessFunction.id || !serverlessFunction.projectId) {
            return;
        }
        try {
            const rules = await ServerlessFunctionOwnerRuleService.findBy({
                query: {
                    projectId: serverlessFunction.projectId,
                    isEnabled: true,
                },
                props: { isRoot: true },
                select: {
                    _id: true,
                    name: true,
                    notifyOwners: true,
                    matchLabels: { _id: true },
                    nameRegexPattern: true,
                    descriptionRegexPattern: true,
                    ownerUsers: { _id: true },
                    ownerTeams: { _id: true },
                },
                limit: 100,
                skip: 0,
            });
            if (rules.length === 0) {
                return;
            }
            const fnWithDetails = await ServerlessFunctionService.findOneById({
                id: serverlessFunction.id,
                select: {
                    name: true,
                    description: true,
                    labels: { _id: true },
                },
                props: { isRoot: true },
            });
            if (!fnWithDetails) {
                return;
            }
            const usersByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            const teamsByNotify = new Map([
                [true, new Set()],
                [false, new Set()],
            ]);
            let anyMatched = false;
            for (const rule of rules) {
                if (!this.doesMatchRule(fnWithDetails, rule)) {
                    continue;
                }
                const notify = rule.notifyOwners !== false;
                for (const user of rule.ownerUsers || []) {
                    if (user.id) {
                        usersByNotify.get(notify).add(user.id.toString());
                        anyMatched = true;
                    }
                }
                for (const team of rule.ownerTeams || []) {
                    if (team.id) {
                        teamsByNotify.get(notify).add(team.id.toString());
                        anyMatched = true;
                    }
                }
            }
            if (!anyMatched) {
                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 ServerlessFunctionOwnerUser();
                    owner.serverlessFunctionId = serverlessFunction.id;
                    owner.projectId = serverlessFunction.projectId;
                    owner.userId = new ObjectID(userId);
                    owner.isOwnerNotified = !notify;
                    await ServerlessFunctionOwnerUserService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
                for (const teamId of teamIds) {
                    const owner = new ServerlessFunctionOwnerTeam();
                    owner.serverlessFunctionId = serverlessFunction.id;
                    owner.projectId = serverlessFunction.projectId;
                    owner.teamId = new ObjectID(teamId);
                    owner.isOwnerNotified = !notify;
                    await ServerlessFunctionOwnerTeamService.create({
                        data: owner,
                        props: { isRoot: true },
                    });
                }
            }
        }
        catch (error) {
            logger.error(`Error applying serverless function owner rules: ${error}`, {
                projectId: (_a = serverlessFunction.projectId) === null || _a === void 0 ? void 0 : _a.toString(),
                serverlessFunctionId: (_b = serverlessFunction.id) === null || _b === void 0 ? void 0 : _b.toString(),
            });
        }
    }
    doesMatchRule(serverlessFunction, rule) {
        if (rule.matchLabels && rule.matchLabels.length > 0) {
            if (!serverlessFunction.labels ||
                serverlessFunction.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 = serverlessFunction.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 &&
            (!serverlessFunction.name ||
                !this.testRegex(rule.nameRegexPattern, serverlessFunction.name))) {
            return false;
        }
        if (rule.descriptionRegexPattern &&
            (!serverlessFunction.description ||
                !this.testRegex(rule.descriptionRegexPattern, serverlessFunction.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 serverless function owner rule: ${pattern}`);
            return false;
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ServerlessFunction]),
    __metadata("design:returntype", Promise)
], ServerlessFunctionOwnerRuleEngineServiceClass.prototype, "applyRulesToServerlessFunction", null);
export default new ServerlessFunctionOwnerRuleEngineServiceClass();
//# sourceMappingURL=ServerlessFunctionOwnerRuleEngineService.js.map