"""Security gate: 401 / 403 / 404 / 422 all speak the SAME structured
triple {error_code, summary, detail} (M8 hardening; 04-architecture
"every route speaks the triple"). A consumer never has to special-case
an auth failure vs a not-found — and an error body never leaks internals.
"""

import uuid

from tests.reporting.conftest import rpt_engine, rpt_url  # noqa: F401
from tests.routers.conftest import as_adi, as_rian, client_factory  # noqa: F401

_REQUIRED_KEYS = {"error_code", "summary", "detail"}


def _assert_triple(body: dict) -> None:
    assert set(body) >= _REQUIRED_KEYS, body
    assert isinstance(body["error_code"], str) and body["error_code"]
    assert isinstance(body["summary"], str) and body["summary"]


def test_401_shape(client):
    resp = client.get("/api/meta")
    assert resp.status_code == 401
    _assert_triple(resp.json())
    assert resp.json()["error_code"] == "NOT_AUTHENTICATED"


def test_403_shape(as_adi):  # noqa: F811
    # CC expenses is owner-only; adi is a worker -> 403 triple.
    resp = as_adi.post("/api/cc/batches", json={"name": "nope"})
    assert resp.status_code == 403
    _assert_triple(resp.json())


def test_404_shape(as_rian):  # noqa: F811
    resp = as_rian.delete(f"/api/saved-views/{uuid.uuid4()}")
    assert resp.status_code == 404
    _assert_triple(resp.json())
    assert resp.json()["error_code"] == "VIEW_NOT_FOUND"


def test_422_shape(as_rian):  # noqa: F811
    resp = as_rian.post(
        "/api/saved-views", json={"page": "not-a-page", "name": "x"}
    )
    assert resp.status_code == 422
    _assert_triple(resp.json())
    assert resp.json()["error_code"] == "BAD_VIEW_PAGE"


def test_error_bodies_do_not_leak_secrets(as_rian):  # noqa: F811
    # A structured error's detail must never echo secret-shaped material.
    resp = as_rian.delete(f"/api/saved-views/{uuid.uuid4()}")
    blob = (resp.text or "").lower()
    for needle in ("secret", "password", "session_secret", "client_secret", "bw_client"):
        assert needle not in blob, f"error body leaked {needle!r}"
