import logging

import sentry_sdk

from app.core.logging import get_request_id


def test_response_gets_a_generated_request_id(client):
    resp = client.get("/api/v1/health")
    assert resp.status_code == 200
    assert resp.headers["x-request-id"]


def test_incoming_request_id_is_echoed_back(client):
    resp = client.get("/api/v1/health", headers={"X-Request-ID": "caller-supplied-id"})
    assert resp.headers["x-request-id"] == "caller-supplied-id"


def test_two_requests_get_different_request_ids(client):
    first = client.get("/api/v1/health").headers["x-request-id"]
    second = client.get("/api/v1/health").headers["x-request-id"]
    assert first != second


def test_log_lines_during_a_request_carry_its_request_id(client, monkeypatch, caplog):
    """app.services.sms logs the OTP in development mode (see
    tests/test_logging_redaction.py) — a real in-request log call, not
    a synthetic one, so this proves the contextvar RequestIdMiddleware
    sets is actually visible deep inside a service function, and that
    it matches the ID the caller sees on the response header."""
    from app.core.config import settings

    monkeypatch.setattr(settings, "environment", "development")
    with caplog.at_level(logging.INFO, logger="yeneb.sms"):
        resp = client.post(
            "/api/v1/auth/signup/start",
            json={"phone": "0912345678", "name": "Someone"},
        )
    assert resp.status_code == 200, resp.text
    sms_records = [r for r in caplog.records if r.name == "yeneb.sms"]
    assert sms_records
    assert sms_records[-1].request_id == resp.headers["x-request-id"]


def test_request_id_contextvar_defaults_to_dash_outside_a_request():
    assert get_request_id() == "-"


def test_unhandled_exception_reports_to_sentry_when_configured(client, monkeypatch):
    """Uses the already-running `client` fixture's app (so the
    fixture's get_redis override is still in place for rate limiting)
    but a fresh raw TestClient for the actual call, same as
    tests/test_error_handling.py — the `client` fixture's own
    TestClient raises server exceptions back into the test instead of
    returning the 500 response a real caller would see."""
    from starlette.testclient import TestClient

    from app.db.session import get_db
    from app.main import app

    captured = {}
    monkeypatch.setattr(
        sentry_sdk,
        "capture_exception",
        lambda exc=None: captured.setdefault("exc", exc),
    )

    class _BrokenSession:
        def execute(self, *args, **kwargs):
            raise RuntimeError("boom")

    def _broken_db():
        yield _BrokenSession()

    app.dependency_overrides[get_db] = _broken_db
    try:
        raw_client = TestClient(app, raise_server_exceptions=False)
        resp = raw_client.get("/api/v1/health/db")
    finally:
        app.dependency_overrides.pop(get_db, None)

    assert resp.status_code == 500
    assert isinstance(captured.get("exc"), RuntimeError)
