"""Integration: the bot's communication Flask layer enforces the shared key,
and the key the bot would *send* (constants.service_headers) is accepted.
"""
import constants
import communication_subroutine as cs


def _client(key="test-secret"):
    cs.API_KEY = key
    return cs.app.test_client()


def test_prepped_tracks_rejected_without_key():
    client = _client()
    resp = client.post(
        "/prepped_tracks", data='["all", "x"]', content_type="application/json"
    )
    assert resp.status_code == 401


def test_prepped_tracks_accepted_with_key():
    client = _client()
    resp = client.post(
        "/prepped_tracks",
        data='["all", "x"]',
        headers={"X-Conjurer-Api-Key": "test-secret"},
        content_type="application/json",
    )
    assert resp.status_code == 200


def test_conjurer_get_is_open():
    client = _client()
    assert client.get("/conjurer").status_code == 200


def test_open_when_key_unset():
    client = _client(key=None)
    resp = client.post(
        "/prepped_tracks", data='["all", "x"]', content_type="application/json"
    )
    assert resp.status_code == 200


def test_bot_service_headers_accepted_by_service(monkeypatch):
    # End-to-end auth contract: the header constants.service_headers() produces
    # is exactly what communication_subroutine._authorize_request() expects.
    monkeypatch.setattr(constants, "API_SHARED_KEY", "shared-xyz")
    cs.API_KEY = "shared-xyz"
    resp = cs.app.test_client().post(
        "/prepped_tracks",
        data='["all", "x"]',
        headers=constants.service_headers(),
        content_type="application/json",
    )
    assert resp.status_code == 200
