"""Unit tests for AppleWalletService."""

import pytest

from app.modules.loyalty.exceptions import InvalidAppleAuthTokenException
from app.modules.loyalty.services.apple_wallet_service import AppleWalletService


class _FakeCard:
    """Lightweight card stub for verify_auth_token tests."""

    def __init__(self, token: str | None) -> None:
        self.apple_auth_token = token


@pytest.mark.unit
@pytest.mark.loyalty
class TestAppleWalletService:
    """Test suite for AppleWalletService."""

    def setup_method(self):
        self.service = AppleWalletService()

    def test_service_instantiation(self):
        """Service can be instantiated."""
        assert self.service is not None


@pytest.mark.unit
@pytest.mark.loyalty
class TestVerifyAuthToken:
    """verify_auth_token must be constant-time and handle missing tokens."""

    def setup_method(self):
        self.service = AppleWalletService()

    def test_correct_token_passes(self):
        card = _FakeCard("correct-token-abc123")
        # Should not raise
        self.service.verify_auth_token(card, "ApplePass correct-token-abc123")

    def test_wrong_token_raises(self):
        card = _FakeCard("correct-token-abc123")
        with pytest.raises(InvalidAppleAuthTokenException):
            self.service.verify_auth_token(card, "ApplePass wrong-token-xyz")

    def test_missing_authorization_header_raises(self):
        card = _FakeCard("correct-token-abc123")
        with pytest.raises(InvalidAppleAuthTokenException):
            self.service.verify_auth_token(card, None)

    def test_malformed_authorization_header_raises(self):
        card = _FakeCard("correct-token-abc123")
        with pytest.raises(InvalidAppleAuthTokenException):
            self.service.verify_auth_token(card, "Bearer correct-token-abc123")

    def test_card_with_no_stored_token_raises(self):
        """A card that never enrolled in Apple Wallet has no token to compare."""
        card = _FakeCard(None)
        with pytest.raises(InvalidAppleAuthTokenException):
            self.service.verify_auth_token(card, "ApplePass anything")
