# ================================================================
# services/orchestrator/app/core/database.py
# ================================================================
"""
Database connection and session management for Orchestrator Service
Minimal database - only for audit trail
"""

from shared.database.base import DatabaseManager
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from .config import settings

# Initialize database manager
database_manager = DatabaseManager(
    database_url=settings.DATABASE_URL,
    echo=settings.DEBUG
)

# Create async session factory
AsyncSessionLocal = async_sessionmaker(
    database_manager.async_engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)


async def get_db() -> AsyncSession:
    """
    Dependency to get database session.
    Used in FastAPI endpoints via Depends(get_db).
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()


async def init_db():
    """Initialize database (create tables if needed)"""
    await database_manager.create_all()


async def close_db():
    """Close database connections"""
    await database_manager.close()
