"""Tests for the API client — error handling, response parsing."""

import pytest
from httpx import Response
from loony.api import ApiError, _raise_for_status


class TestRaiseForStatus:
    def test_200_does_not_raise(self) -> None:
        resp = Response(200, json={"ok": True})
        _raise_for_status(resp)  # should not raise

    def test_401_raises_with_message(self) -> None:
        resp = Response(401, json={"error": {"type": "authentication_error", "message": "Bad token"}})
        with pytest.raises(ApiError) as exc_info:
            _raise_for_status(resp)
        assert exc_info.value.message == "Bad token"
        assert exc_info.value.status_code == 401

    def test_404_raises(self) -> None:
        resp = Response(404, json={"error": {"type": "not_found", "message": "Service not found."}})
        with pytest.raises(ApiError) as exc_info:
            _raise_for_status(resp)
        assert "not found" in exc_info.value.message.lower()

    def test_500_raises(self) -> None:
        resp = Response(500, json={"error": {"type": "server_error", "message": "Internal error"}})
        with pytest.raises(ApiError):
            _raise_for_status(resp)

    def test_non_json_error(self) -> None:
        resp = Response(502, text="Bad Gateway")
        with pytest.raises(ApiError):
            _raise_for_status(resp)

    def test_malformed_error_json(self) -> None:
        resp = Response(400, json={"unexpected": "format"})
        with pytest.raises(ApiError):
            _raise_for_status(resp)
