from typing import cast

import pytest
from aws_lambda_typing.events import APIGatewayProxyEventV1

from iisi_app_core import JwtTokenHandler, Principal, RequestScope, Role, UnauthorizedError, principal, set_principal


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


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

    with RequestScope():
        set_principal(Principal.system())
        handler(cast(APIGatewayProxyEventV1, {"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(cast(APIGatewayProxyEventV1, {"headers": {"Authorization": "Token abc"}}))
