import pytest
from jose.exceptions import JWTError
from pytest_mock import MockFixture
from src.routers.auth_helpers import get_key, get_kid

HELPERS_PATH = "src.routers.auth_helpers."


class TestAuthHelpers:
    def test_get_kid_success(self, mocker: MockFixture) -> None:
        mocker.patch(
            f"{HELPERS_PATH}jwt.get_unverified_header",
            return_value={"kid": "kid-123"},
        )

        kid = get_kid("token")

        assert kid == "kid-123"

    def test_get_kid_raises_when_kid_missing(self, mocker: MockFixture) -> None:
        mocker.patch(
            f"{HELPERS_PATH}jwt.get_unverified_header",
            return_value={},
        )

        with pytest.raises(JWTError, match="'kid' not found"):
            get_kid("token")

    def test_get_key_success(self, mocker: MockFixture) -> None:
        mock_key = mocker.Mock()
        mocker.patch(
            f"{HELPERS_PATH}requests.get",
        ).return_value.json.return_value = {
            "keys": [{"kid": "kid-123", "kty": "RSA"}],
        }
        mocker.patch(f"{HELPERS_PATH}jwk.construct", return_value=mock_key)

        key = get_key("kid-123", "https://example.com/.well-known/jwks.json")

        assert key == mock_key

    def test_get_key_raises_when_key_not_found(self, mocker: MockFixture) -> None:
        mocker.patch(
            f"{HELPERS_PATH}requests.get",
        ).return_value.json.return_value = {
            "keys": [{"kid": "other-kid", "kty": "RSA"}],
        }

        with pytest.raises(JWTError, match="Matching key not found"):
            get_key("kid-123", "https://example.com/.well-known/jwks.json")
