import traceback
from typing import Generator

from src.core.database import SessionLocal


def get_db() -> Generator:
    """Starts and ends session in each route that needs database access."""
    db = SessionLocal()
    try:
        db.begin()
        yield db
    except Exception as e:
        print("*******************************")
        print("MIDDLEWARE DB EXCEPTION == ", repr(e))
        print("THE TRACEBACK=====================", traceback.format_exc())
        print("*******************************")
        db.rollback()
        raise  # Re-raise the exception to let FastAPI handle it
    finally:
        db.close()

