# app/core/database.py
"""
Database configuration and session management.

This module provides classes and functions for:
- Database engine creation and configuration
- Session management with connection pooling
- Database dependency for FastAPI routes
"""

import logging

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

from .config import settings

engine = create_engine(settings.database_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

logger = logging.getLogger(__name__)


def get_db():
    """
    Database session dependency for FastAPI routes.

    Yields a database session and ensures proper cleanup.
    Handles exceptions and rolls back transactions on error.
    """
    db = SessionLocal()
    try:
        yield db
    except Exception as e:
        logger.error(f"Database session error: {e}")
        db.rollback()
        raise
    finally:
        db.close()
