"""
Unit tests for authentication endpoints
"""

import pytest
from unittest.mock import patch, MagicMock


class TestAuth:
    """Test authentication endpoints"""

    def test_login_success(self, client, db):
        """Test successful login"""
        # Mock external auth service with proper Pydantic models
        from app.services.external_auth_service import AuthResponse, UserInfo

        user_info = UserInfo(
            id="test-id-123",
            name="Test User",
            email="test@example.com"
        )
        auth_response = AuthResponse(
            access_token="test-token",
            id_token="test-id-token",
            expires_in=3600,
            token_type="Bearer",
            user_info=user_info,
            issued_at="2025-11-16T10:00:00Z",
            expires_at="2025-11-16T11:00:00Z"
        )

        with patch('app.routers.auth.external_auth_service.authenticate_user') as mock_auth:
            mock_auth.return_value = (True, auth_response, None)

            response = client.post('/api/v2/auth/login', json={
                'username': 'test@example.com',
                'password': 'password123'
            })

            assert response.status_code == 200
            data = response.json()
            assert 'access_token' in data
            assert data['token_type'] == 'bearer'
            assert 'user' in data

    def test_login_invalid_credentials(self, client):
        """Test login with invalid credentials"""
        with patch('app.routers.auth.external_auth_service.authenticate_user') as mock_auth:
            mock_auth.return_value = (False, None, 'Invalid credentials')

            response = client.post('/api/v2/auth/login', json={
                'username': 'test@example.com',
                'password': 'wrongpassword'
            })

            assert response.status_code == 401
            assert 'detail' in response.json()

    def test_get_me(self, client, auth_token):
        """Test get current user info"""
        response = client.get(
            '/api/v2/auth/me',
            headers={'Authorization': f'Bearer {auth_token}'}
        )

        assert response.status_code == 200
        data = response.json()
        assert 'email' in data
        assert 'display_name' in data

    def test_get_me_unauthorized(self, client):
        """Test get current user without token"""
        response = client.get('/api/v2/auth/me')
        assert response.status_code == 403

    def test_logout(self, client, auth_token):
        """Test logout"""
        response = client.post(
            '/api/v2/auth/logout',
            headers={'Authorization': f'Bearer {auth_token}'}
        )

        assert response.status_code == 200
        data = response.json()
        # When no session_id is provided, logs out all sessions
        assert 'message' in data
        assert 'Logged out' in data['message']
