# app/database.py
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker, declarative_base
from app.config import settings

# Ensure DATABASE_URL is set before proceeding
if not settings.DATABASE_URL:
    raise ValueError("DATABASE_URL is not configured in settings.")

# Create the SQLAlchemy async engine
# pool_recycle=3600 helps prevent stale connections on some DBs
engine = create_async_engine(
    settings.DATABASE_URL,
    echo=False,  # Disable SQL query logging for production (use DEBUG log level to enable)
    future=True, # Use SQLAlchemy 2.0 style features
    pool_recycle=3600, # Optional: recycle connections after 1 hour
    pool_pre_ping=True # Add this line to ensure connections are live
)

# Create a configured "Session" class
# expire_on_commit=False prevents attributes from expiring after commit
AsyncSessionLocal = sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autoflush=False,
    autocommit=False,
)

# Base class for our ORM models
Base = declarative_base()

# Dependency to get DB session in path operations
async def get_session() -> AsyncSession: # type: ignore
    """
    Dependency function that yields an AsyncSession for read-only operations.
    Ensures the session is closed after the request.
    """
    async with AsyncSessionLocal() as session:
        yield session
    # The 'async with' block handles session.close() automatically.

async def get_transactional_session() -> AsyncSession: # type: ignore
    """
    Dependency function that yields an AsyncSession and manages a transaction.
    Commits the transaction if the request handler succeeds, otherwise rollbacks.
    Ensures the session is closed after the request.
    
    This follows the FastAPI-DB strategy for endpoint-level transaction management.
    """
    async with AsyncSessionLocal() as session:
        async with session.begin():
            yield session
            # Transaction is automatically committed on success or rolled back on exception

# Alias for backward compatibility
get_db = get_session