from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

# Create the engine with sensible defaults for MySQL under load
engine = create_async_engine(
    settings.DATABASE_URL,
    pool_pre_ping=True,                     # avoid stale connections
    pool_recycle=280,                       # recycle before MySQL wait_timeout
    pool_size=settings.POOL_SIZE,           # base pool
    max_overflow=settings.POOL_MAX_OVERFLOW,# burst capacity
    pool_timeout=settings.POOL_TIMEOUT,     # wait before giving up
    echo=settings.SQLALCHEMY_ECHO,
    future=True,
)

# Use AsyncSession to enable asynchronous database operations
AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    autocommit=False,
    autoflush=False,
    expire_on_commit=False,  # This is a common setting for async sessions
    future=True,
)

async def get_db():
    """
    FastAPI dependency for asynchronous database sessions.
    
    This function will automatically handle the lifecycle of the session,
    including closing it after the request is complete.
    """
    async with AsyncSessionLocal() as db:
        try:
            yield db
        finally:
            await db.close()

