from unittest.mock import MagicMock

from neurovault.security.rbac import Permission, ROLE_PERMISSIONS, UserManager


def test_create_and_authenticate_user():
    storage = MagicMock()
    storage.get_user_by_token_hash.return_value = {
        "username": "alice",
        "role": "writer",
        "active": True,
    }
    storage.get_device_token_by_hash.return_value = None

    manager = UserManager(storage)
    result = manager.create_user("alice", role="writer")
    assert result["role"] == "writer"
    assert len(result["token"]) == 64

    user = manager.authenticate(result["token"])
    assert user is not None
    storage.get_user_by_token_hash.assert_called()


def test_permission_check():
    manager = UserManager(MagicMock())
    user = {
        "username": "bob",
        "role": "reader",
        "permissions": ROLE_PERMISSIONS["reader"],
    }
    assert manager.check_permission(user, Permission.READ)
    assert not manager.check_permission(user, Permission.WRITE)
