# /opt/docker/dev/service_finder/backend/app/db/session.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from app.core.config import settings
from typing import AsyncGenerator

engine = create_async_engine(
    settings.DATABASE_URL,
    echo=False,
    future=True,
    pool_size=30,      # A robotok száma miatt
    max_overflow=20,
    pool_pre_ping=True,
    pool_reset_on_return='rollback'
)

AsyncSessionLocal = async_sessionmaker(
    engine, 
    class_=AsyncSession, 
    expire_on_commit=False, 
    autoflush=False
)

async def get_db() -> AsyncGenerator[AsyncSession, None]:
    async with AsyncSessionLocal() as session:
        # Start with a clean transaction state by rolling back any failed transaction
        try:
            await session.rollback()
        except Exception:
            # If rollback fails, it's probably because there's no transaction
            # This is fine, just continue
            pass
        
        try:
            yield session
        except Exception:
            # If any exception occurs, rollback the transaction
            await session.rollback()
            raise
        finally:
            # Ensure session is closed
            await session.close()