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

from unittest.mock import MagicMock, patch

import httpx
import pytest

from appxen_cli.client import AppXenClient


class TestAppXenClient:

    def test_auth_header_set(self):
        """Client sets Bearer token header."""
        client = AppXenClient("axgw_test_key", "http://localhost:8000")
        assert client._client.headers["authorization"] == "Bearer axgw_test_key"
        client.close()

    def test_user_agent_set(self):
        """Client sets User-Agent header."""
        client = AppXenClient("axgw_test_key", "http://localhost:8000")
        assert "appxen-cli" in client._client.headers["user-agent"]
        client.close()

    def test_context_manager(self):
        """Client works as context manager."""
        with AppXenClient("axgw_test_key", "http://localhost:8000") as client:
            assert client._client is not None

    @patch("httpx.Client.request")
    def test_health(self, mock_request):
        """Health endpoint returns parsed JSON."""
        mock_resp = MagicMock(spec=httpx.Response)
        mock_resp.status_code = 200
        mock_resp.json.return_value = {"status": "healthy"}
        mock_resp.raise_for_status = MagicMock()
        mock_request.return_value = mock_resp

        with AppXenClient("axgw_test", "http://localhost:8000") as client:
            result = client.health()
            assert result["status"] == "healthy"

    @patch("httpx.Client.request")
    def test_list_sources(self, mock_request):
        """List sources passes params correctly."""
        mock_resp = MagicMock(spec=httpx.Response)
        mock_resp.status_code = 200
        mock_resp.json.return_value = {"sources": [], "total": 0}
        mock_resp.raise_for_status = MagicMock()
        mock_request.return_value = mock_resp

        with AppXenClient("axgw_test", "http://localhost:8000") as client:
            result = client.list_sources(limit=10, offset=5, search="test")
            assert result["total"] == 0

        call_kwargs = mock_request.call_args
        params = call_kwargs.kwargs.get("params", {})
        assert params["limit"] == 10
        assert params["offset"] == 5
        assert params["search"] == "test"

    @patch("httpx.Client.request")
    def test_search(self, mock_request):
        """Search sends correct payload."""
        mock_resp = MagicMock(spec=httpx.Response)
        mock_resp.status_code = 200
        mock_resp.json.return_value = {"results": []}
        mock_resp.raise_for_status = MagicMock()
        mock_request.return_value = mock_resp

        with AppXenClient("axgw_test", "http://localhost:8000") as client:
            result = client.search("deploy guide", top_k=3)
            assert "results" in result

        call_kwargs = mock_request.call_args
        json_body = call_kwargs.kwargs.get("json", {})
        assert json_body["query"] == "deploy guide"
        assert json_body["top_k"] == 3
