"""SQLAlchemy engine/session setup. FastAPI dependency `get_db` yields one session per request.

AUDIT (StockLab overhaul, Part 25 — PostgreSQL production optimization): connection pooling was
previously hardcoded to `pool_pre_ping=True` only, with SQLAlchemy's library defaults for
everything else (`pool_size=5`, `max_overflow=10`, no `pool_recycle`, `pool_timeout=30`) — workable
for local dev but not documented or tunable for a small production server. Now sourced from
`Settings` (`DB_POOL_SIZE`/`DB_MAX_OVERFLOW`/`DB_POOL_TIMEOUT_SECONDS`/`DB_POOL_RECYCLE_SECONDS`/
`DB_POOL_PRE_PING`, all env-overridable) so the target Debian 13 / Podman deployment can size the
pool for its actual RAM/connection budget without a code change — see docs/DEPLOYMENT.md §9.
"""
from __future__ import annotations

from collections.abc import Generator

from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker

from app.core.config import get_settings

settings = get_settings()

engine = create_engine(
    settings.DATABASE_URL,
    pool_pre_ping=settings.DB_POOL_PRE_PING,
    pool_size=settings.DB_POOL_SIZE,
    max_overflow=settings.DB_MAX_OVERFLOW,
    pool_timeout=settings.DB_POOL_TIMEOUT_SECONDS,
    pool_recycle=settings.DB_POOL_RECYCLE_SECONDS,
    future=True,
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)


def get_db() -> Generator[Session, None, None]:
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
