"""
Database transaction context manager for consistent transaction handling.

This module provides a context manager that automatically handles
database commits and rollbacks, ensuring data consistency.
"""
from contextlib import contextmanager
from sqlalchemy.orm import Session
from typing import Generator
from ...shared.config.logging_config import get_logger

logger = get_logger(__name__)


@contextmanager
def transaction(db: Session) -> Generator[Session, None, None]:
    """
    Context manager for database transactions.
    Automatically commits on success, rolls back on error.
    
    Usage:
        with transaction(db):
            db.add(booking)
            # Auto-commits on success, rolls back on error
    
    Args:
        db: SQLAlchemy database session
        
    Yields:
        The database session
        
    Raises:
        Any exception that occurs during the transaction
    """
    try:
        yield db
        db.commit()
        logger.debug('Transaction committed successfully')
    except Exception as e:
        db.rollback()
        logger.error(f'Transaction rolled back due to error: {type(e).__name__}: {str(e)}', exc_info=True)
        raise

