// ==========================================
// Switchboard Core — SDK: RBAC Gate
// ==========================================
// Synchronous permission checking for render paths.
//
// Factory: createCan(authRef)
// ==========================================

/**
 * Create the RBAC gate.
 *
 * @param {object} authRef — the auth module (reads .permissions, .user, .teams)
 * @returns {{ can, isAdmin, isTeamAdmin }}
 */
export function createCan(authRef) {

    /**
     * Check if the current user has a permission.
     * Synchronous — reads from cached permission set.
     *
     * @param {string} permission — e.g. 'model.use', 'kb.read', 'channel.create'
     * @returns {boolean}
     */
    function can(permission) {
        return authRef.permissions.has(permission);
    }

    /**
     * Is the current user a platform admin?
     * v0.2.0: Uses RBAC grant instead of legacy role field.
     * @returns {boolean}
     */
    function isAdmin() {
        return authRef.permissions.has('surface.admin.access');
    }

    /**
     * Is the current user an admin of the given team?
     * @param {string} teamId
     * @returns {boolean}
     */
    function isTeamAdmin(teamId) {
        const teams = authRef.teams;
        if (!teams || !teams.length) return false;
        const t = teams.find(t => t.id === teamId);
        return t?.my_role === 'admin';
    }

    return { can, isAdmin, isTeamAdmin };
}
