"""Hub HTTP tests — the end-to-end proof of the security boundary.

The CRITICAL test: a non-super-admin gets 403 FORBIDDEN (and zero rows) on
EVERY /api/hub/* endpoint. Proven through the real app so it also pins the
wiring — the tenant-exempt path (no NO_TENANT interception) plus the
super-admin gate — not just the service function in isolation.
"""

from __future__ import annotations

import pytest

from tests.hub.conftest import HUB_ENDPOINTS


def _get(client, endpoint):
    return client.get(f"/api/hub/{endpoint}")


@pytest.mark.parametrize("endpoint", HUB_ENDPOINTS)
def test_super_admin_gets_rows(hub_http, endpoint):
    rian = hub_http.make("rian", is_super=True)
    res = _get(rian, endpoint)
    assert res.status_code == 200
    assert isinstance(res.json()["rows"], list) and res.json()["rows"]


@pytest.mark.parametrize("endpoint", HUB_ENDPOINTS)
def test_non_super_admin_403_every_endpoint(hub_http, endpoint):
    """THE one that cannot be wrong: a partner account is refused, sees no
    rows, and the refusal is a clean FORBIDDEN (never NO_TENANT)."""
    adi = hub_http.make("adi", is_super=False)
    res = _get(adi, endpoint)
    assert res.status_code == 403
    body = res.json()
    assert body["error_code"] == "FORBIDDEN"
    assert "rows" not in body


@pytest.mark.parametrize("endpoint", HUB_ENDPOINTS)
def test_super_admin_viewing_as_non_super_403(hub_http, endpoint):
    """A super admin (rian) impersonating a non-super-admin (adi) is ALSO
    refused — impersonation must never open a cross-tenant surface."""
    rian_as_adi = hub_http.make("rian", is_super=True, view_as="adi")
    res = _get(rian_as_adi, endpoint)
    assert res.status_code == 403
    assert res.json()["error_code"] == "FORBIDDEN"


def test_super_admin_projects_span_all_tenants(hub_http):
    rian = hub_http.make("rian", is_super=True)
    rows = _get(rian, "projects").json()["rows"]
    assert {r["tenant"] for r in rows} == {"Bowden Works", "PlusROI"}


def test_super_admin_organization_detail(hub_http):
    rian = hub_http.make("rian", is_super=True)
    copernic_id = hub_http.ns.copernic.id
    res = rian.get(f"/api/hub/organizations/{copernic_id}/detail")
    assert res.status_code == 200
    body = res.json()
    assert {p["tenant"] for p in body["client_profiles"]} == {
        "Bowden Works",
        "PlusROI",
    }
    assert body["tenant_vendors"] == []


def test_non_super_admin_organization_detail_403(hub_http):
    adi = hub_http.make("adi", is_super=False)
    copernic_id = hub_http.ns.copernic.id
    res = adi.get(f"/api/hub/organizations/{copernic_id}/detail")
    assert res.status_code == 403
    assert res.json()["error_code"] == "FORBIDDEN"
