"""
Pytest configuration for integration tests.

Provides shared fixtures for database testing with proper async session management.
Uses NullPool to avoid asyncpg connection reuse issues in tests.

Reference: https://github.com/MagicStack/asyncpg/issues/863#issuecomment-1229220920
"""
import pytest
import pytest_asyncio
from uuid import uuid4
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.pool import NullPool

from app.database.operations import DatabaseOperations
from app.config import get_settings


settings = get_settings()

# Create test-specific engine with NullPool to avoid connection reuse issues
test_engine = create_async_engine(
    settings.database_url,
    poolclass=NullPool,  # Each test gets a fresh connection - fixes asyncpg concurrency issue
    echo=False
)

# Create test-specific session factory
TestAsyncSessionLocal = async_sessionmaker(
    test_engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)


@pytest_asyncio.fixture
async def db_ops(monkeypatch):
    """
    Provide DatabaseOperations instance for each test.

    Monkeypatches the database session module to use NullPool test engine.
    This prevents asyncpg "another operation is in progress" errors.
    """
    # Import the session module
    from app.database import session

    # Monkeypatch the AsyncSessionLocal to use our test session factory
    monkeypatch.setattr(session, 'AsyncSessionLocal', TestAsyncSessionLocal)

    # Now DatabaseOperations will use the test session factory
    return DatabaseOperations()


@pytest.fixture
def unique_game_id():
    """Generate a unique game ID for each test"""
    return uuid4()
