"""Database engine and session helpers.

This module provides:
- A SQLAlchemy engine configured from environment settings.
- A declarative base for all ORM models.
- A session generator for FastAPI dependency injection.
"""

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

from .config import settings


class Base(DeclarativeBase):
    """Base class for all SQLAlchemy ORM models."""

    pass


def get_engine():
    """Create a SQLAlchemy engine based on the configured database URL.

    For SQLite we set `check_same_thread=False` so the dev server can
    safely use a single connection across threads.
    """
    connect_args = {}
    if settings.database_url.startswith("sqlite"):
        connect_args = {"check_same_thread": False}
    return create_engine(settings.database_url, pool_pre_ping=True, connect_args=connect_args)


def get_sessionmaker():
    """Create a sessionmaker bound to the current engine."""
    return sessionmaker(autocommit=False, autoflush=False, bind=get_engine())


def get_db():
    """Yield a database session for request-scoped usage.

    The session is always closed after the request completes, ensuring
    connections are returned to the pool cleanly.
    """
    db = get_sessionmaker()()
    try:
        yield db
    finally:
        db.close()
