"""
Async SQLAlchemy engine and session factory for DocuVault.

The engine reads DATABASE_URL (restricted docuvault_app user — DML only).
The Alembic migration runner uses DATABASE_MIGRATE_URL (DDL user) separately.

Key settings:
  pool_pre_ping=True       — detect stale connections before use
  expire_on_commit=False   — prevent MissingGreenlet errors after commit in
                             async context (RESEARCH.md Pitfall 1)
"""
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession

from config import settings

engine = create_async_engine(
    settings.database_url,  # postgresql+psycopg://docuvault_app:...@postgres/docuvault
    pool_pre_ping=True,     # detect stale connections before use
    echo=False,
)

AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,  # prevent MissingGreenlet errors after commit (Pitfall 1)
)
