"""Database configuration and session management."""

import os
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base

# URL dal environment o default per Docker
DATABASE_URL = os.getenv(
    "DATABASE_URL", "postgresql+asyncpg://postgres:postgres@postgres:5432/mockupaws"
)

# Debug: stampa la DATABASE_URL all'avvio
print(f"DEBUG - DATABASE_URL: {DATABASE_URL}", flush=True)

# Engine async
engine = create_async_engine(
    DATABASE_URL,
    echo=False,  # Set to True for debug SQL
    future=True,
    pool_size=20,
    max_overflow=0,
)

# Session factory
AsyncSessionLocal = async_sessionmaker(
    engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False,
)

# Base per i modelli
Base = declarative_base()


# Dependency per FastAPI
async def get_db() -> AsyncSession:
    """Dependency that provides a database session."""
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()
