"""
Async SQLAlchemy session factory.

get_db() is the FastAPI dependency used everywhere a DB session is needed.
The session is committed on clean exit, rolled back on any exception.
"""

from __future__ import annotations

from collections.abc import AsyncGenerator

from sqlalchemy.ext.asyncio import (
    AsyncSession,
    async_sessionmaker,
    create_async_engine,
)

from app.config import get_settings

settings = get_settings()

engine = create_async_engine(
    settings.database_url,
    echo=False,   # set True only when debugging SQL locally
    pool_pre_ping=True,                # detect stale connections before use
    pool_size=10,
    max_overflow=20,
    pool_recycle=3600,                 # recycle connections after 1 h
)

# Exported so background tasks that need a fresh session can import it
AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,  # objects stay usable after commit
    autocommit=False,
    autoflush=False,
)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """
    FastAPI dependency: yields an async DB session.
    Commits on clean return, rolls back on exception.
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
