import json

from andrea_svc_auth import client


class _FakeResp:
    def __init__(self, status):
        self.status = status

    def __enter__(self):
        return self

    def __exit__(self, *a):
        return False


def test_post_event_attaches_key_and_payload(monkeypatch):
    cap = {}

    def fake_urlopen(req, timeout=None):
        cap["url"] = req.full_url
        cap["headers"] = {k.lower(): v for k, v in req.header_items()}
        cap["body"] = json.loads(req.data)
        cap["method"] = req.get_method()
        return _FakeResp(202)

    monkeypatch.setattr(client.urllib.request, "urlopen", fake_urlopen)
    st = client.post_event("http://gem:8787/event", source="pool-worker",
                           body="hi", severity="warning", api_key="K3Y")
    assert st == 202
    assert cap["method"] == "POST" and cap["url"] == "http://gem:8787/event"
    assert cap["headers"].get("x-agent-key") == "K3Y"
    assert cap["body"] == {"source": "pool-worker", "severity": "warning", "body": "hi"}


def test_post_event_env_key_and_extra(monkeypatch):
    cap = {}
    monkeypatch.setattr(client.os, "getenv", lambda k, d="": "ENVKEY" if k == client.API_KEY_ENV else d)

    def fake_urlopen(req, timeout=None):
        cap["headers"] = {k.lower(): v for k, v in req.header_items()}
        cap["body"] = json.loads(req.data)
        return _FakeResp(200)
    monkeypatch.setattr(client.urllib.request, "urlopen", fake_urlopen)

    client.post_event("http://g/event", source="build", body="b",
                      extra={"host": "w2295", "kind": "missing-box"})
    assert cap["headers"].get("x-agent-key") == "ENVKEY"
    assert cap["body"]["host"] == "w2295" and cap["body"]["kind"] == "missing-box"


def test_post_event_no_key_omits_header(monkeypatch):
    cap = {}
    monkeypatch.setattr(client.os, "getenv", lambda k, d="": "")

    def fake_urlopen(req, timeout=None):
        cap["headers"] = {k.lower() for k, _ in req.header_items()}
        return _FakeResp(401)
    monkeypatch.setattr(client.urllib.request, "urlopen", fake_urlopen)

    client.post_event("http://g/event", source="x", body="y")
    assert "x-agent-key" not in cap["headers"]      # fail-closed by omission
