# services/external/app/core/database.py
"""
External Service Database Configuration using shared database manager
"""

import structlog
from contextlib import asynccontextmanager
from typing import AsyncGenerator

from app.core.config import settings
from shared.database.base import DatabaseManager, Base

logger = structlog.get_logger()

# Create database manager instance
database_manager = DatabaseManager(
    database_url=settings.DATABASE_URL,
    service_name="external-service"
)

async def get_db():
    """
    Database dependency for FastAPI - using shared database manager
    """
    async for session in database_manager.get_db():
        yield session


async def init_db():
    """Initialize database tables using shared database manager"""
    try:
        logger.info("Initializing External Service database...")
        
        # Import all models to ensure they're registered
        from app.models import weather, traffic  # noqa: F401
        
        # Create all tables using database manager
        await database_manager.create_tables(Base.metadata)
            
        logger.info("External Service database initialized successfully")
        
    except Exception as e:
        logger.error("Failed to initialize database", error=str(e))
        raise


async def close_db():
    """Close database connections using shared database manager"""
    try:
        await database_manager.close_connections()
        logger.info("Database connections closed")
    except Exception as e:
        logger.error("Error closing database connections", error=str(e))


@asynccontextmanager
async def get_db_transaction():
    """
    Context manager for database transactions using shared database manager
    """
    async with database_manager.get_session() as session:
        try:
            async with session.begin():
                yield session
        except Exception as e:
            logger.error("Transaction error", error=str(e))
            raise


@asynccontextmanager
async def get_background_session():
    """
    Context manager for background tasks using shared database manager
    """
    async with database_manager.get_background_session() as session:
        yield session


async def health_check():
    """Database health check using shared database manager"""
    return await database_manager.health_check()