"""SQLAlchemy 2.0 async 엔진 + 세션 팩토리.

API(main.py)와 워커(worker.py)가 공유한다. asyncpg 드라이버 사용.
"""
from __future__ import annotations

from collections.abc import AsyncGenerator

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

from .config import settings


class Base(DeclarativeBase):
    pass


engine = create_async_engine(settings.sqlalchemy_url(), echo=False, pool_pre_ping=True)

SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)


async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """FastAPI 의존성: 요청당 세션."""
    async with SessionLocal() as session:
        yield session


async def init_db() -> None:
    """테이블 생성 (없으면). 단순화를 위해 alembic 대신 create_all 사용."""
    from . import models  # noqa: F401  (모델 등록)

    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
