"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildAbilityFromScopes = void 0;
const parseScopes_1 = require("./parseScopes");
const scopes_1 = require("./scopes");
const handlePatConfigApplication = (context, builder) => {
    const { pat } = context?.permissionsConfig || {};
    const hasPatRule = builder.rules.find((rule) => rule.action === 'manage' && rule.subject === 'PersonalAccessToken');
    if (!hasPatRule &&
        pat?.enabled &&
        context.organizationRole &&
        pat?.allowedOrgRoles?.includes(context.organizationRole)) {
        builder.can('manage', 'PersonalAccessToken');
    }
};
/**
 * Apply scope-based abilities to a CASL ability builder
 * @param scopeNames - Array of scope names to apply
 * @param context - Context containing organization, project, user, and space access information
 * @param builder - CASL ability builder to add permissions to
 */
const applyScopeAbilities = (context, builder) => {
    const scopeMap = (0, scopes_1.getAllScopeMap)({ isEnterprise: context.isEnterprise });
    context.scopes.forEach((scopeName) => {
        const scope = scopeMap[scopeName];
        if (!scope)
            return;
        const [action, subject] = (0, parseScopes_1.parseScope)(scopeName);
        const conditionsList = scope.getConditions(context);
        // Apply each condition set if there are any
        if (conditionsList.length === 0) {
            builder.can(action, subject);
        }
        else {
            conditionsList.forEach((conditions) => {
                builder.can(action, subject, conditions);
            });
        }
    });
    handlePatConfigApplication(context, builder);
};
/**
 * Apply CASL abilities from scopes to a builder
 * @param context - Context containing organization, project, user, and space access information
 * @param builder - CASL ability builder to add permissions to
 */
const buildAbilityFromScopes = (context, builder) => {
    const isEnterprise = context.isEnterprise ?? false;
    const scopes = (0, parseScopes_1.parseScopes)({
        scopes: context.scopes,
        isEnterprise,
    });
    const parsedContext = {
        ...context,
        scopes,
        isEnterprise,
    };
    applyScopeAbilities(parsedContext, builder);
};
exports.buildAbilityFromScopes = buildAbilityFromScopes;
//# sourceMappingURL=scopeAbilityBuilder.js.map