from fastapi.testclient import TestClient

from app.db.session import get_db
from app.main import app


class _BrokenSession:
    def execute(self, *args, **kwargs):
        raise RuntimeError("boom - should never leak to the client")


def _broken_db():
    yield _BrokenSession()


def test_unhandled_exception_returns_generic_500():
    """An unexpected bug (here, simulated via a broken get_db override)
    must never leak its type/message/traceback to the client — only a
    generic body, with the real detail going to the server log instead
    (see app.main.unhandled_exception_handler).

    Starlette's ServerErrorMiddleware re-raises the original exception
    after sending the response, specifically so an ASGI server/process
    supervisor still sees it for its own logging even though the
    client already got a proper response — the default TestClient
    surfaces that re-raise as a Python exception in the test itself,
    so this needs raise_server_exceptions=False to actually inspect
    the response a real client would receive."""
    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
    body = resp.json()
    assert body["detail"] == "Internal server error."
    assert body["request_id"]  # correlates this response with the server log
    assert "RuntimeError" not in resp.text
    assert "boom" not in resp.text


def test_intentional_http_exceptions_are_unaffected(client):
    """The catch-all handler must not shadow FastAPI's normal handling
    of HTTPException — a routine 404 still returns its own message,
    not the generic 500 body."""
    resp = client.post("/api/v1/orders/00000000-0000-0000-0000-000000000000/cancel")
    assert resp.status_code in (401, 403)  # unauthenticated, not 500
