from __future__ import annotations

from collections.abc import AsyncGenerator
from typing import TYPE_CHECKING

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from core.config.settings import config

if TYPE_CHECKING:
    from sqlalchemy.ext.asyncio import AsyncEngine

engine: AsyncEngine = create_async_engine(
    config.database_url,
    echo=config.runtime.sql_log_queries,
    pool_pre_ping=True,
)

AsyncSessionLocal: async_sessionmaker[AsyncSession] = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autoflush=False,
)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """Dependency that provides a database session.

    The session is automatically closed when the request completes.
    Note: The caller (service layer) is responsible for commit/rollback.
    """
    async with AsyncSessionLocal() as session:
        yield session
