"""Tests for the base HTTP client."""

import pytest
import responses

from purpleflea.client import APIError, PurpleFleaClient


BASE = "https://api.purpleflea.com"


@responses.activate
def test_get_request():
    responses.get(f"{BASE}/ping", json={"status": "ok"})
    client = PurpleFleaClient("test-key")
    result = client.get("/ping")
    assert result == {"status": "ok"}
    assert responses.calls[0].request.headers["Authorization"] == "Bearer test-key"


@responses.activate
def test_post_request():
    responses.post(f"{BASE}/items", json={"id": "1"})
    client = PurpleFleaClient("test-key")
    result = client.post("/items", name="widget")
    assert result == {"id": "1"}
    assert responses.calls[0].request.body == b'{"name": "widget"}'


@responses.activate
def test_put_request():
    responses.put(f"{BASE}/items/1", json={"id": "1", "name": "updated"})
    client = PurpleFleaClient("test-key")
    result = client.put("/items/1", name="updated")
    assert result == {"id": "1", "name": "updated"}


@responses.activate
def test_delete_request():
    responses.delete(f"{BASE}/items/1", json={"deleted": True})
    client = PurpleFleaClient("test-key")
    result = client.delete("/items/1")
    assert result == {"deleted": True}


@responses.activate
def test_client_error_raises_api_error():
    responses.get(f"{BASE}/bad", status=404, body="Not Found")
    client = PurpleFleaClient("test-key")
    with pytest.raises(APIError) as exc_info:
        client.get("/bad")
    assert exc_info.value.status_code == 404


@responses.activate
def test_retry_on_server_error():
    responses.get(f"{BASE}/flaky", status=500, body="fail")
    responses.get(f"{BASE}/flaky", json={"ok": True})
    client = PurpleFleaClient("test-key", max_retries=2)
    result = client.get("/flaky")
    assert result == {"ok": True}
    assert len(responses.calls) == 2


@responses.activate
def test_exhausted_retries():
    for _ in range(3):
        responses.get(f"{BASE}/down", status=502, body="bad gateway")
    client = PurpleFleaClient("test-key", max_retries=3)
    with pytest.raises(APIError, match="retries"):
        client.get("/down")


def test_custom_base_url():
    client = PurpleFleaClient("key", base_url="https://custom.example.com/")
    assert client.base_url == "https://custom.example.com"


def test_context_manager():
    with PurpleFleaClient("key") as client:
        assert client.api_key == "key"
