"""
Tests for authentication and token management
"""

from unittest.mock import Mock, patch
from datetime import datetime, timedelta

from aphub_sdk.auth import TokenManager


def test_token_manager_initialization():
    """Test token manager initialization"""
    manager = TokenManager(
        base_url="http://test.com",
        access_token="test-token",
        refresh_token="refresh-token",
    )
    assert manager.access_token == "test-token"
    assert manager.refresh_token == "refresh-token"


def test_token_expiry_check():
    """Test token expiry checking"""
    manager = TokenManager(base_url="http://test.com")
    
    # No expiry set, should be expired
    assert manager.is_token_expired() is True
    
    # Set future expiry
    manager._token_expiry = datetime.now() + timedelta(hours=1)
    assert manager.is_token_expired() is False
    
    # Set past expiry
    manager._token_expiry = datetime.now() - timedelta(hours=1)
    assert manager.is_token_expired() is True


def test_token_refresh_success():
    """Test successful token refresh"""
    manager = TokenManager(
        base_url="http://test.com",
        refresh_token="refresh-token",
    )
    
    mock_response = Mock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "access_token": "new-access-token",
        "refresh_token": "new-refresh-token",
    }
    
    with patch('httpx.Client') as mock_client:
        mock_client.return_value.__enter__.return_value.post.return_value = mock_response
        result = manager.refresh_access_token()
        assert result is True
        assert manager.access_token == "new-access-token"


def test_token_refresh_failure():
    """Test token refresh failure"""
    manager = TokenManager(
        base_url="http://test.com",
        refresh_token="refresh-token",
    )
    
    mock_response = Mock()
    mock_response.status_code = 401
    
    with patch('httpx.Client') as mock_client:
        mock_client.return_value.__enter__.return_value.post.return_value = mock_response
        result = manager.refresh_access_token()
        assert result is False


def test_get_valid_token():
    """Test getting valid token"""
    manager = TokenManager(
        base_url="http://test.com",
        access_token="test-token",
    )
    
    # Token not expired
    manager._token_expiry = datetime.now() + timedelta(hours=1)
    token = manager.get_valid_token()
    assert token == "test-token"
    
    # Token expired, refresh fails
    manager._token_expiry = datetime.now() - timedelta(hours=1)
    manager.refresh_token = None
    token = manager.get_valid_token()
    assert token is None

