import json

import pytest

from relay_gateway.manage_keys import add_key, list_keys, revoke
from relay_gateway.keys import hash_token


def test_add_key_writes_hashed_entry(tmp_path):
    kf = tmp_path / "relay_keys.json"
    token = add_key(kf, name="cn", level="sre")
    body = json.loads(kf.read_text())
    assert hash_token(token) in body
    assert body[hash_token(token)] == {"name": "cn", "level": "sre"}


def test_add_key_rejects_bad_level(tmp_path):
    with pytest.raises(ValueError):
        add_key(tmp_path / "k.json", name="x", level="bogus")


def test_revoke_removes_by_name(tmp_path):
    kf = tmp_path / "relay_keys.json"
    add_key(kf, name="cn", level="sre")
    add_key(kf, name="keep", level="tss")
    removed = revoke(kf, "cn")
    assert removed == 1
    names = {e["name"] for e in list_keys(kf)}
    assert names == {"keep"}
