import { RBACPolicy } from '../rbac.mjs';
import { logger } from '../utils/logger.mjs';

class HeadlessRBACClient {
    _subscriptionService;
    cachedPolicy;
    policyPromise;
    constructor(cachedConfig, dynamicConfig, _subscriptionService){
        this._subscriptionService = _subscriptionService;
        this.cachedPolicy = cachedConfig.rbacPolicy ? RBACPolicy.fromJSON(cachedConfig.rbacPolicy) : null;
        this.policyPromise = dynamicConfig.then((data)=>{
            if (!data.rbacPolicy) {
                logger.error('Unable to retrieve RBAC policy from servers. Assuming caller has no permissions.');
                return new RBACPolicy([], []);
            }
            // Update the existing policy too, so isAuthorizedSync will be up-to-date
            this.cachedPolicy = RBACPolicy.fromJSON(data.rbacPolicy);
            return this.cachedPolicy;
        });
    }
    allPermissions() {
        return this.policyPromise.then((policy)=>policy.allPermissionsForCaller(this.roleIds()));
    }
    isAuthorizedSync = (resourceId, action)=>{
        return !!this.cachedPolicy?.callerIsAuthorized(this.roleIds(), resourceId, action);
    };
    isAuthorized = (resourceId, action)=>{
        return this.policyPromise.then((policy)=>policy.callerIsAuthorized(this.roleIds(), resourceId, action));
    };
    roleIds() {
        const user = this._subscriptionService.getUser();
        if (!user) {
            return [];
        }
        // Although user.roles is guaranteed to exist for fresh data, there is a chance
        // that the user stored in localstorage clientside comes from before roles were added to
        // the API response - in which case user.roles will be undefined and this will crash
        // TODO: [AUTH-2294] We can safely remove this ~3mos after RBAC is released
        return user.roles ?? [];
    }
}

export { HeadlessRBACClient };
//# sourceMappingURL=HeadlessRBACClient.mjs.map
