import pytest
from aegro.api_client import AegroClient
from aegro.errors import AegroAPIError


@pytest.fixture
def client():
    return AegroClient(base_url="https://app.aegro.com.br", timeout=5.0, max_retries=1)


@pytest.mark.asyncio
async def test_get_success(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/farms", json={"key": "farm-1", "name": "Test Farm"}
    )
    result = await client.get("/pub/v1/farms", api_key="test-key")
    assert result == {"key": "farm-1", "name": "Test Farm"}
    request = httpx_mock.get_request()
    assert request.headers["Aegro-Public-API-Key"] == "test-key"


@pytest.mark.asyncio
async def test_post_success(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/crops/filter", json={"items": [], "totalItemsCount": 0}
    )
    result = await client.post(
        "/pub/v1/crops/filter", api_key="test-key", json_body={"requiredPageNumber": 1}
    )
    assert result == {"items": [], "totalItemsCount": 0}


@pytest.mark.asyncio
async def test_204_returns_none(client, httpx_mock):
    httpx_mock.add_response(url="https://app.aegro.com.br/pub/v1/farms", status_code=204)
    result = await client.get("/pub/v1/farms", api_key="key")
    assert result is None


@pytest.mark.asyncio
async def test_201_returns_json(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/tags",
        status_code=201,
        json={"key": "t1", "name": "Urgente"},
    )
    result = await client.post("/pub/v1/tags", api_key="test-key", json_body={"name": "Urgente"})
    assert result == {"key": "t1", "name": "Urgente"}


@pytest.mark.asyncio
async def test_401_raises_error(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/farms",
        status_code=401,
        json={"message": "Invalid token"},
    )
    with pytest.raises(AegroAPIError) as exc_info:
        await client.get("/pub/v1/farms", api_key="bad-key")
    assert exc_info.value.status_code == 401
    assert "API Key invalida" in exc_info.value.user_message


@pytest.mark.asyncio
async def test_500_retries_then_raises(client, httpx_mock):
    httpx_mock.add_response(url="https://app.aegro.com.br/pub/v1/farms", status_code=500, json={})
    httpx_mock.add_response(url="https://app.aegro.com.br/pub/v1/farms", status_code=500, json={})
    with pytest.raises(AegroAPIError) as exc_info:
        await client.get("/pub/v1/farms", api_key="key")
    assert exc_info.value.status_code == 500
    assert exc_info.value.retryable is True


@pytest.mark.asyncio
async def test_put_success(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/assets/fuel-supplies/fs1",
        json={"key": "fs1", "updated": True},
    )
    result = await client.put(
        "/pub/v1/assets/fuel-supplies/fs1",
        api_key="test-key",
        json_body={"occurrenceDate": "2025-01-01"},
    )
    assert result == {"key": "fs1", "updated": True}
    request = httpx_mock.get_request()
    assert request.method == "PUT"
    assert request.headers["Aegro-Public-API-Key"] == "test-key"


@pytest.mark.asyncio
async def test_delete_success(client, httpx_mock):
    httpx_mock.add_response(
        url="https://app.aegro.com.br/pub/v1/installments/inst1",
        status_code=204,
    )
    result = await client.delete("/pub/v1/installments/inst1", api_key="test-key")
    assert result is None
    request = httpx_mock.get_request()
    assert request.method == "DELETE"
