"""Database setup with SQLAlchemy async."""
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.orm import declarative_base
from .config import settings

# Convert sync URL to async
DATABASE_URL = settings.DATABASE_URL.replace("postgresql://", "postgresql+asyncpg://")

engine = create_async_engine(
    DATABASE_URL, 
    echo=settings.DEBUG, 
    pool_size=10, 
    max_overflow=20,
    pool_pre_ping=True,  # Test connection before using
    pool_recycle=3600    # Recycle connections after 1 hour
)
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

Base = declarative_base()

async def get_db() -> AsyncSession:
    async with async_session() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise
        finally:
            await session.close()

async def init_db():
    # Import all models here to ensure they are registered with Base.metadata
    from app.models import User, Organization, OrganizationMember, Integration, Issue, AuditLog  # noqa
    
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)
