"""Brief 2026-10-21: three roles, and payment keys that only the Admin sees (sheet 2)."""
import pytest

from core.db import get_db
from services import payment_keys_service as pk

SK = "sk_test_" + "a1B2c3D4e5F6g7H8i9J0k1L2"
PK = "pk_test_" + "z9Y8x7W6v5U4t3S2r1Q0p9O8"
WH = "whsec_" + "m1N2b3V4c5X6z7L8k9J0h1G2"


@pytest.fixture(autouse=True)
def _clean_keys():
    yield
    with get_db() as conn:
        conn.execute("DELETE FROM app_secrets")
        conn.commit()


async def test_the_operator_has_their_own_password(client):
    assert (await client.post("/api/admin/login", json={"password": "nope"})).status_code == 401
    r = await client.post("/api/admin/login", json={"password": "test-operator-pw"})
    assert r.status_code == 200 and r.json()["role"] == "operator"


async def test_the_operator_never_sees_revenue(client, admin_headers, operator_headers):
    admin_stats = (await client.get("/api/admin/stats", headers=admin_headers)).json()
    op_stats = (await client.get("/api/admin/stats", headers=operator_headers)).json()
    assert admin_stats["revenue"] is not None
    assert op_stats["revenue"] is None and op_stats["revenue_share"] is None and op_stats["revenue_share_pct"] is None
    assert "revenue_share_pct" not in op_stats["settings"]
    settings = (await client.get("/api/admin/settings", headers=operator_headers)).json()
    assert "revenue_share_pct" not in settings["settings"]
    assert all(f["key"] != "revenue_share_pct" for f in settings["fields"])
    schools = (await client.get("/api/admin/schools", headers=operator_headers)).json()["schools"]
    assert all(s["revenue"] is None for s in schools)
    assert (await client.get("/api/director/dashboard", headers=operator_headers)).status_code == 403


@pytest.mark.parametrize("method,url,body", [
    ("PUT", "/api/admin/settings", {"settings": {"school_address": "x"}}),
    ("GET", "/api/admin/payment-keys", None),
    ("PUT", "/api/admin/payment-keys", {"stripe_secret_key": SK}),
    ("POST", "/api/admin/payment-keys/test", None),
    ("POST", "/api/admin/schools", {"name": "Nope"}),
    ("GET", "/api/admin/system", None),
    ("PUT", "/api/admin/protection", {}),
])
async def test_the_operator_cannot_reach_admin_only_routes(client, operator_headers, method, url, body):
    r = await client.request(method, url, json=body, headers=operator_headers)
    assert r.status_code == 403, (url, r.text)


async def test_the_operator_keeps_the_daily_routes(client, operator_headers):
    for url in ("/api/admin/orders", "/api/admin/classes", "/api/admin/families", "/api/admin/cards",
                "/api/admin/audit", "/api/admin/formats"):
        assert (await client.get(url, headers=operator_headers)).status_code == 200, url


async def test_keys_are_encrypted_masked_and_never_returned(client, admin_headers):
    r = await client.put("/api/admin/payment-keys",
                         json={"stripe_secret_key": SK, "stripe_public_key": PK, "stripe_webhook_secret": WH},
                         headers=admin_headers)
    assert r.status_code == 200, r.text
    for secret in (SK, PK, WH):
        assert secret not in r.text
    keys = r.json()["keys"]
    assert keys["stripe_secret_key"] == {"set": True, "masked": "••••" + SK[-4:], "source": "interface"}
    assert (await client.get("/api/admin/payment-keys", headers=admin_headers)).text.count(SK) == 0
    with get_db() as conn:                      # what is in the database is not the key
        stored = [row["value_enc"] for row in conn.execute("SELECT value_enc FROM app_secrets")]
    assert len(stored) == 3 and all(SK not in s and PK not in s for s in stored)
    assert pk.stripe_secret() == SK and pk.portal_public_key() == PK and pk.stripe_webhook_secret() == WH


async def test_the_gallery_gets_the_public_key_only(client, admin_headers):
    await client.put("/api/admin/payment-keys", json={"stripe_public_key": PK, "stripe_secret_key": SK}, headers=admin_headers)
    r = await client.get("/api/portal/payment-config")
    assert r.json() == {"publishable_key": PK} and SK not in r.text


async def test_an_empty_field_keeps_the_current_key(client, admin_headers):
    await client.put("/api/admin/payment-keys", json={"stripe_secret_key": SK}, headers=admin_headers)
    r = await client.put("/api/admin/payment-keys", json={"stripe_secret_key": "", "stripe_webhook_secret": WH},
                         headers=admin_headers)
    assert r.json()["changed"] == ["stripe_webhook_secret"] and pk.stripe_secret() == SK


@pytest.mark.parametrize("body", [
    {"stripe_secret_key": "not-a-key"}, {"stripe_secret_key": "sk_test_short"}, {"stripe_public_key": SK},
    {"stripe_secret_key": "sk_live_" + "q" * 24, "stripe_public_key": PK},      # live secret with a test public key
])
async def test_bad_keys_are_refused_and_nothing_is_saved(client, admin_headers, body):
    r = await client.put("/api/admin/payment-keys", json=body, headers=admin_headers)
    assert r.status_code == 400
    assert pk.status()["stripe_secret_key"]["source"] != "interface"


async def test_a_key_change_goes_to_the_journal_without_the_key(client, admin_headers):
    await client.put("/api/admin/payment-keys", json={"stripe_secret_key": SK}, headers=admin_headers)
    ev = (await client.get("/api/admin/audit?action=payment_keys", headers=admin_headers)).json()["events"]
    assert ev and ev[0]["details"] == {"keys": ["stripe_secret_key"]} and ev[0]["severity"] == "critical"
    assert SK not in str(ev)


async def test_the_connection_test_asks_stripe(client, admin_headers, monkeypatch):
    import stripe
    await client.put("/api/admin/payment-keys", json={"stripe_secret_key": SK, "stripe_public_key": PK}, headers=admin_headers)
    seen = {}
    monkeypatch.setattr(stripe.Balance, "retrieve", staticmethod(lambda **kw: seen.update(kw) or {}))
    r = await client.post("/api/admin/payment-keys/test", headers=admin_headers)
    assert r.json()["ok"] is True and r.json()["mode"] == "test" and seen == {"api_key": SK}

    def refuse(**kw):
        raise stripe.AuthenticationError("bad key")
    monkeypatch.setattr(stripe.Balance, "retrieve", staticmethod(refuse))
    r = await client.post("/api/admin/payment-keys/test", headers=admin_headers)
    assert r.json()["ok"] is False and SK not in r.text


async def test_orders_use_the_key_saved_in_the_interface(client, admin_headers, monkeypatch):
    import main
    await client.put("/api/admin/payment-keys", json={"stripe_secret_key": SK, "stripe_public_key": PK}, headers=admin_headers)
    seen = {}

    class _PI:
        client_secret, id = "cs_x", "pi_x_iface"
    monkeypatch.setattr(main.stripe.PaymentIntent, "create", staticmethod(lambda **kw: seen.update(kw) or _PI()))
    body = {"family_code": "TST-1001", "customer_email": "a@example.com", "class_name": "CE1 A",
            "items": [{"photo_filename": "portrait.jpg", "format_id": "digital", "format_label": "Digital",
                       "quantity": 1, "unit_price": 7.0, "is_magic": False}], "total": 7.0}
    r = await client.post("/api/portal/orders", json=body)
    assert r.status_code == 200, r.text
    assert seen["api_key"] == SK
