from __future__ import annotations

from typing import Generator

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel, Session


@pytest.fixture(scope="session")
def sqlite_url(tmp_path_factory: pytest.TempPathFactory) -> str:
    db_path = tmp_path_factory.mktemp("db") / "test.db"
    return f"sqlite:///{db_path}"


@pytest.fixture(autouse=True)
def sqlite_db(sqlite_url: str) -> Generator[None, None, None]:
    engine = create_engine(sqlite_url, connect_args={"check_same_thread": False})
    from services.common import db as common_db

    common_db.engine = engine
    common_db.SessionLocal = sessionmaker(bind=engine, class_=Session, expire_on_commit=False)

    import services.api.app as api_app
    import services.game.app as game_app
    import services.analytics.app as analytics_app
    import services.api.models  # noqa: F401
    import services.game.models  # noqa: F401

    api_app.engine = engine
    api_app.SessionLocal = common_db.SessionLocal
    game_app.engine = engine
    analytics_app.engine = engine

    SQLModel.metadata.drop_all(engine)
    SQLModel.metadata.create_all(engine)
    yield
    SQLModel.metadata.drop_all(engine)
