"""Shared fixtures for integration tests — in-memory SQLite server."""

from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from evalkit.server.app import create_app
from evalkit.server.db.base import Base
from evalkit.server.db.session import get_db


@pytest.fixture
def client():
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    Base.metadata.create_all(engine)
    TestSession = sessionmaker(bind=engine)

    def _get_db():
        db = TestSession()
        try:
            yield db
        finally:
            db.close()

    app = create_app()
    app.dependency_overrides[get_db] = _get_db

    # Patch SessionLocal in route modules so background tasks
    # also use the in-memory test database instead of the file-based default.
    with (
        patch("evalkit.server.routes.api.SessionLocal", TestSession),
        patch("evalkit.server.routes.traces.SessionLocal", TestSession),
    ):
        yield TestClient(app, raise_server_exceptions=False)

    Base.metadata.drop_all(engine)
