"""Async database engine and session factory."""

from __future__ import annotations

from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

from gps_denied.config import get_settings


def _build_engine():
    settings = get_settings()
    connect_args = {}
    if "sqlite" in settings.db.url:
        connect_args["check_same_thread"] = False

    eng = create_async_engine(
        settings.db.url,
        echo=settings.db.echo,
        connect_args=connect_args,
    )

    # Enable FK enforcement for SQLite (required for ON DELETE CASCADE)
    @event.listens_for(eng.sync_engine, "connect")
    def _set_sqlite_pragma(dbapi_connection, connection_record):
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()

    return eng


engine = _build_engine()

async_session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)


async def get_session() -> AsyncSession:  # noqa: ANN201 — used as FastAPI dependency
    """Yield an async session (for use as a FastAPI dependency)."""
    async with async_session_factory() as session:
        yield session
