"""MySQL：SQLAlchemy 2.0 async engine + session factory。
仅 DB_BACKEND=mysql 时使用；mongodb 模式下本模块不被引用。
"""

from collections.abc import AsyncGenerator

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

from src.config import settings


class Base(DeclarativeBase):
    """所有 MySQL ORM 模型的基类。"""


engine = create_async_engine(settings.MYSQL_DSN, pool_size=10, pool_recycle=3600)
async_session = async_sessionmaker(engine, expire_on_commit=False)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """FastAPI 依赖：每请求一个 session。"""
    async with async_session() as session:
        yield session


async def close_engine() -> None:
    await engine.dispose()
