"""One silent retry for a dropped erp-api connection.

Reported live: "full" in the apply flow answered "I'm unable to reach the HR
system right now", and the same message sent again a moment later worked -
the signature of a pooled keep-alive connection the server had already
closed. The retry must never duplicate a write, and never re-hit a slow or
erroring erp-api.
"""

from unittest.mock import patch

import httpx
import pytest

import services.erp_client as erp_client


class _FlakyHttp:
    """Fails the first `fail_times` calls with `exc`, then answers 200."""

    def __init__(self, exc, fail_times=1):
        self.exc, self.fail_times, self.calls = exc, fail_times, 0

    async def request(self, method, url, **kwargs):
        self.calls += 1
        if self.calls <= self.fail_times:
            raise self.exc
        return httpx.Response(200, json={"success": True, "data": {}},
                              request=httpx.Request(method, url))


@pytest.fixture(autouse=True)
def _configured(monkeypatch):
    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)


async def _call(http, method="GET"):
    with patch.object(erp_client, "_http", http):
        return await erp_client._request(method, "/api/v1/ai/leave/context", "tok")


@pytest.mark.parametrize("exc", [
    httpx.RemoteProtocolError("Server disconnected without sending a response."),
    httpx.ReadError("connection reset"),
    httpx.ConnectError("connection refused"),
])
async def test_a_read_survives_one_dropped_connection(exc):
    http = _FlakyHttp(exc)

    result = await _call(http)

    assert result["http_status"] == 200
    assert http.calls == 2


async def test_a_read_that_fails_twice_is_still_reported_unavailable():
    http = _FlakyHttp(httpx.RemoteProtocolError("gone"), fail_times=2)

    with pytest.raises(erp_client.ErpApiUnavailable):
        await _call(http)
    assert http.calls == 2


@pytest.mark.parametrize("exc", [
    httpx.RemoteProtocolError("Server disconnected without sending a response."),
    httpx.ReadError("connection reset"),
])
async def test_a_write_is_never_resent_once_it_may_have_arrived(exc):
    """apply/cancel/approve: erp-api may already have acted on it."""
    http = _FlakyHttp(exc)

    with pytest.raises(erp_client.ErpApiUnavailable):
        await _call(http, method="POST")
    assert http.calls == 1


async def test_a_write_is_retried_when_the_connection_never_opened():
    http = _FlakyHttp(httpx.ConnectError("connection refused"))

    result = await _call(http, method="POST")

    assert result["http_status"] == 200
    assert http.calls == 2


@pytest.mark.parametrize("exc", [httpx.ReadTimeout("slow"), httpx.ConnectTimeout("slow")])
async def test_a_timeout_is_never_retried(exc):
    http = _FlakyHttp(exc)

    with pytest.raises(erp_client.ErpApiTimeout):
        await _call(http)
    assert http.calls == 1
