"""Tenant isolation: a principal can only ever read/write its own workspace."""

from __future__ import annotations


def test_audit_log_is_workspace_scoped(client, helpers):
    a = helpers.bootstrap_owner(client, email="a@example.com", name="Alpha")
    b = helpers.bootstrap_owner(client, email="b@example.com", name="Beta")

    a_audit = client.get("/audit", headers=helpers.headers(a["access_token"])).json()
    b_audit = client.get("/audit", headers=helpers.headers(b["access_token"])).json()

    a_slugs = {e["metadata"].get("slug") for e in a_audit}
    b_slugs = {e["metadata"].get("slug") for e in b_audit}
    assert "alpha" in a_slugs and "beta" not in a_slugs
    assert "beta" in b_slugs and "alpha" not in b_slugs


def test_members_list_is_workspace_scoped(client, helpers):
    a = helpers.bootstrap_owner(client, email="a@example.com", name="Alpha")
    b = helpers.bootstrap_owner(client, email="b@example.com", name="Beta")
    helpers.add_member(client, a["access_token"], email="only-a@example.com", role="viewer")

    b_members = client.get("/members", headers=helpers.headers(b["access_token"])).json()
    emails = {m["email"] for m in b_members}
    assert "only-a@example.com" not in emails
    assert emails == {"b@example.com"}


def test_api_keys_are_workspace_scoped(client, helpers):
    a = helpers.bootstrap_owner(client, email="a@example.com", name="Alpha")
    b = helpers.bootstrap_owner(client, email="b@example.com", name="Beta")

    client.post(
        "/api-keys",
        json={"name": "a-key", "scopes": ["read"]},
        headers=helpers.headers(a["access_token"]),
    )
    b_keys = client.get("/api-keys", headers=helpers.headers(b["access_token"])).json()
    assert b_keys == []


def test_api_key_only_authorizes_its_own_workspace(client, helpers):
    a = helpers.bootstrap_owner(client, email="a@example.com", name="Alpha")
    helpers.bootstrap_owner(client, email="b@example.com", name="Beta")

    created = client.post(
        "/api-keys",
        json={"name": "a-key", "scopes": ["read"]},
        headers=helpers.headers(a["access_token"]),
    ).json()

    audit = client.get("/audit", headers={"X-API-Key": created["plaintext"]}).json()
    slugs = {e["metadata"].get("slug") for e in audit}
    assert "alpha" in slugs
    assert "beta" not in slugs
