"""Default-deny at the framework layer.

A route is protected because the auth middleware denies everything under /api/ and
/auth/ by default — not because a route remembered to guard itself. These tests pin
that contract: protected routes 401 for an anonymous caller, the tiny PUBLIC allow-
list is reachable, and — the load-bearing one — an UNKNOWN /api/ path is 401 for
anon (not 404), which proves a newly-added route is protected the instant it exists,
before anyone wires a guard onto it.
"""

from tests.conftest import as_user


def _code(resp):
    """error_code from either a middleware JSONResponse (top-level) or a route
    HTTPException ({"detail": {...}})."""
    body = resp.json()
    d = body.get("detail")
    return d.get("error_code") if isinstance(d, dict) else body.get("error_code")


def test_anonymous_is_denied_on_app_route(client):
    """A signed-out caller never reaches an auth-required app route."""
    r = client.get("/api/whoami")
    assert r.status_code == 401
    assert _code(r) == "NOT_AUTHENTICATED"


def test_anonymous_is_denied_on_admin_route(client):
    """The admin surface (/api/bw/*) is behind the same default-deny wall."""
    r = client.get("/api/bw/accounts")
    assert r.status_code == 401
    assert _code(r) == "NOT_AUTHENTICATED"


def test_public_meta_is_reachable_anonymously(client):
    """/api/meta renders on the signed-out screen, so it must be public."""
    r = client.get("/api/meta")
    assert r.status_code == 200
    body = r.json()
    assert body["app"] and "has_instances" in body


def test_public_me_probe_is_reachable_anonymously(client):
    """/api/bw/me is the SPA's 'am I signed in?' probe — public, returns
    authenticated:false for an anon caller (never a 401)."""
    r = client.get("/api/bw/me")
    assert r.status_code == 200
    assert r.json()["authenticated"] is False


def test_healthz_is_public(client):
    """The health probe carries no data and must answer without a session."""
    r = client.get("/healthz")
    assert r.status_code == 200
    assert r.text == "ok"


def test_unknown_api_path_is_401_for_anon_not_404(client):
    """The invariant that makes new routes safe by default: an unknown /api/ path
    is DENIED (401), not reported as 404. If this were 404, a freshly-added route
    would be reachable until someone remembered to guard it."""
    r = client.get("/api/does-not-exist")
    assert r.status_code == 401
    assert _code(r) == "NOT_AUTHENTICATED"


def test_known_app_route_reachable_once_signed_in(client):
    """The flip side of default-deny: with a session, the same route is reachable —
    proving the wall is the session check, not a blanket block."""
    as_user(client, "rian")
    r = client.get("/api/whoami")
    assert r.status_code == 200
    assert r.json()["username"] == "rian"
