"""Integration test fixtures using the running postgres from docker-compose."""

from __future__ import annotations

import pytest_asyncio
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

# Points to the docker-compose postgres (must be running: docker compose up postgres)
TEST_DSN = "postgresql+asyncpg://acef:acef@localhost:5432/acef"


@pytest_asyncio.fixture
async def db_engine():
    """Function-scoped engine — avoids event loop cross-contamination."""
    engine = create_async_engine(TEST_DSN, echo=False, pool_pre_ping=True)
    yield engine
    await engine.dispose()


@pytest_asyncio.fixture
async def db_session(db_engine):
    """Session backed by a transaction that rolls back after every test."""
    async with db_engine.begin() as conn:
        session = AsyncSession(bind=conn, expire_on_commit=False)
        try:
            yield session
        finally:
            await session.close()
            await conn.rollback()
