"""Pytest fixtures for integration tests."""

from __future__ import annotations

from collections.abc import AsyncGenerator

import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from support.db_utils import (
    cleanup_test_schema,
    create_test_engine,
    create_test_session_factory,
    get_or_create_container,
    initialize_test_schema,
    stop_container,
)


@pytest.fixture
async def session_factory() -> AsyncGenerator[async_sessionmaker[AsyncSession], None]:
    """Create a session factory and initialize the database schema."""
    _, database_url = get_or_create_container()

    engine = create_test_engine(database_url)

    async with engine.begin() as conn:
        await initialize_test_schema(conn)

    yield create_test_session_factory(engine)

    # Cleanup - drop schema to reset for next test
    async with engine.begin() as conn:
        await cleanup_test_schema(conn)

    await engine.dispose()


@pytest.fixture
async def session(
    session_factory: async_sessionmaker[AsyncSession],
) -> AsyncGenerator[AsyncSession, None]:
    """Provide a database session for each test."""
    async with session_factory() as session:
        yield session
        # Rollback any uncommitted changes
        await session.rollback()


def pytest_sessionfinish(session: pytest.Session, exitstatus: int) -> None:
    """Cleanup container after all tests complete."""
    stop_container()
