from __future__ import annotations

import pytest

from iisi_app_core.authz import Principal, Role
from iisi_app_core.context import principal, set_principal
from iisi_app_core.exceptions import UnauthorizedError
from iisi_app_core.handlers.jwt import JwtTokenHandler


def setup_function() -> None:
    set_principal(Principal.guest())


def test_jwt_handler_sets_guest_when_authorization_header_missing() -> None:
    set_principal(Principal.system())
    handler = JwtTokenHandler(public_key="unused")

    handler({"headers": {}})

    assert principal().role is Role.GUEST
    assert principal().name == "guest"


def test_jwt_handler_raises_on_invalid_auth_header_type() -> None:
    handler = JwtTokenHandler(public_key="unused")

    with pytest.raises(UnauthorizedError, match="Bearer"):
        handler({"headers": {"Authorization": "Token abc"}})

