import fakeredis
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool

from app.api.v1.endpoints import tracking as tracking_endpoint
from app.core.config import settings
from app.db.redis import get_redis
from app.db.session import Base, get_db
from app.main import app


@pytest.fixture(autouse=True)
def _no_real_notifications(monkeypatch):
    """app.services.sms, app.services.email, and app.services.payments.chapa
    make a real API call whenever their key is set — and any of them
    could be set in the real .env, which pydantic-settings loads for
    *any* process run from this directory, pytest included. Without
    this, every OTP-triggering test (nearly all of them) would try to
    send a real SMS/email, and every checkout test would try to hit
    Chapa's real payment API. db_engine/db_session/client above
    isolate DB and Redis the same way — this extends that to the
    external calls not behind a FastAPI dependency override. Chapa
    isn't configured in .env yet, but this is here proactively so it
    stays safe the moment it is."""
    monkeypatch.setattr(settings, "sms_ethiopia_api_key", "")
    monkeypatch.setattr(settings, "smtp_password", "")
    monkeypatch.setattr(settings, "chapa_secret_key", "")
    monkeypatch.setattr(settings, "chapa_webhook_secret", "")
    monkeypatch.setattr(settings, "google_oauth_client_id", "")
    monkeypatch.setattr(settings, "fcm_project_id", "")
    monkeypatch.setattr(settings, "fcm_service_account_json", "")


@pytest.fixture()
def db_engine():
    """A fresh in-memory SQLite database per test. StaticPool keeps a
    single shared connection alive for the engine's lifetime, so the
    `client` and `db_session` fixtures below — even though each opens
    its own Session — see the same in-memory database."""
    engine = create_engine(
        "sqlite:///:memory:",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    Base.metadata.create_all(bind=engine)
    yield engine
    Base.metadata.drop_all(bind=engine)


@pytest.fixture()
def db_session(db_engine):
    """Direct DB access for a test to seed rows the API can't create
    itself (e.g. an admin/superadmin account, since there's no signup
    endpoint for those — see app.commands.seed_superadmin)."""
    TestingSessionLocal = sessionmaker(
        autocommit=False, autoflush=False, bind=db_engine
    )
    session = TestingSessionLocal()
    try:
        yield session
    finally:
        session.close()


@pytest.fixture()
def client(db_engine, monkeypatch):
    TestingSessionLocal = sessionmaker(
        autocommit=False, autoflush=False, bind=db_engine
    )

    def override_get_db():
        db = TestingSessionLocal()
        try:
            yield db
        finally:
            db.close()

    # A fresh fake Redis per test, same reasoning as db_engine above:
    # without this, rate-limit counters (see app.services.rate_limit)
    # would persist across tests and between test runs, since every
    # TestClient request shares one fake IP — a handful of tests
    # calling login/signup back to back would trip real rate limits on
    # each other. Both clients share one FakeServer so the WebSocket
    # ticket flow (mint via the sync client, redeem via the async one
    # — see app.services.tracking) sees the same in-memory data.
    fake_server = fakeredis.FakeServer()
    fake_redis = fakeredis.FakeRedis(server=fake_server, decode_responses=True)
    fake_async_redis = fakeredis.aioredis.FakeRedis(
        server=fake_server, decode_responses=True
    )

    def override_get_redis():
        return fake_redis

    app.dependency_overrides[get_db] = override_get_db
    app.dependency_overrides[get_redis] = override_get_redis
    monkeypatch.setattr(tracking_endpoint, "get_async_redis", lambda: fake_async_redis)
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()
