import asyncio
from typing import AsyncGenerator

from alembic import command
from alembic.config import Config

from src.core.config import settings
from typing import AsyncGenerator

from src.db.base import SessionLocal


async def get_db() -> AsyncGenerator:
    db = SessionLocal()
    try:
        yield db
        await db.commit()
    except Exception:
        await db.rollback()
        raise
    finally:
        await db.close()


async def run_migrations() -> None:
    alembic_cfg = Config("alembic.ini")
    await asyncio.to_thread(command.upgrade, alembic_cfg, "head")


async def create_tables() -> None:
    if not settings.DEBUG:
        await run_migrations()
