# backend/app/core/admin_database.py
"""
Admin database engine — connects as resolutionflow_admin (BYPASSRLS).

Use ONLY where explicit application-level access control makes database-layer
tenant filtering unnecessary: /admin/* endpoints, internal tooling, and public
endpoints that enforce their own authorization before returning data (e.g.
share access via opaque token + visibility check).
"""
from collections.abc import AsyncGenerator

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

from app.core.config import settings

admin_engine = create_async_engine(
    settings.ADMIN_DATABASE_URL,
    echo=settings.DEBUG,
    future=True,
)

_admin_session_factory = async_sessionmaker(
    admin_engine,
    class_=AsyncSession,
    expire_on_commit=False,
)


async def get_admin_db() -> AsyncGenerator[AsyncSession, None]:
    """Yield an admin DB session (BYPASSRLS). See module docstring for approved use cases."""
    async with _admin_session_factory() as session:
        try:
            yield session
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()
