"""erp-api's own reply must reach the user, not be replaced by
"I'm unable to reach the HR system right now".

That sentence is correct for a connection failure and wrong for everything
else: it blames infrastructure for a business rule, and it invites a retry of
something that can never succeed. erp-api answers refusals through sendInfo()
with a real explanation, and before this the exception carried only the status
code — the body went to the call log and nowhere else.
"""

import httpx
import pytest

import services.erp_client as erp_client


# ── extract_erp_message: the shapes erp-api actually sends ───────────────────

@pytest.mark.parametrize("body,expected", [
    ({"message": "Attendance is locked for this date. Contact HR."},
     "Attendance is locked for this date. Contact HR."),
    ({"data": {"message": "You can only view your own team."}},
     "You can only view your own team."),
    ({"error": "Invalid date format"}, "Invalid date format"),
    ({"detail": "Not permitted"}, "Not permitted"),
    # Whitespace-only is not a message.
    ({"message": "   "}, None),
    # No message to find — the caller keeps its own wording.
    ({"data": {"summary_cards": {}}}, None),
    ({}, None),
    (None, None),
    ("<html>502 Bad Gateway</html>", None),
    ([1, 2, 3], None),
])
def test_extract_erp_message_reads_the_real_shapes(body, expected):
    assert erp_client.extract_erp_message(body) == expected


def test_top_level_message_wins_over_nested():
    body = {"message": "outer", "data": {"message": "inner"}}
    assert erp_client.extract_erp_message(body) == "outer"


# ── unavailable_message: what the user is actually told ──────────────────────

def test_a_business_refusal_is_reported_in_erp_apis_own_words():
    exc = erp_client.ErpApiUnavailable(
        "erp-api returned 403", status_code=403,
        body={"message": "You can only view your own team."})
    assert erp_client.unavailable_message(exc) == "You can only view your own team."


def test_a_genuine_outage_still_gets_the_infrastructure_sentence():
    """No reply at all — connection error, timeout, proxy HTML. Here the
    generic sentence is the honest one."""
    exc = erp_client.ErpApiUnavailable("connection refused")
    assert erp_client.unavailable_message(exc) == erp_client.UNAVAILABLE_FALLBACK
    assert exc.status_code is None


def test_a_caller_can_override_the_fallback():
    exc = erp_client.ErpApiUnavailable("connection refused")
    assert erp_client.unavailable_message(exc, "custom wording") == "custom wording"


def test_the_exception_still_constructs_with_a_message_alone():
    """Every existing `raise ErpApiUnavailable(str(e))` must keep working —
    status_code and body are keyword-only with defaults."""
    exc = erp_client.ErpApiUnavailable("ERP_API_URL not configured")
    assert str(exc) == "ERP_API_URL not configured"
    assert exc.status_code is None and exc.body is None
    assert erp_client.unavailable_message(exc) == erp_client.UNAVAILABLE_FALLBACK


def test_unauthorized_is_still_an_unavailable_subclass():
    """Callers relying on `except ErpApiUnavailable` must keep catching 401s."""
    assert issubclass(erp_client.ErpApiUnauthorized, erp_client.ErpApiUnavailable)


# ── the raise site actually attaches the body ────────────────────────────────

async def test_a_raised_error_carries_erps_response_body(monkeypatch):
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(500, json={"message": "Payroll service is degraded"})

    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_http",
                        httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    with pytest.raises(erp_client.ErpApiUnavailable) as exc_info:
        await erp_client._request("GET", "/api/v1/ai/anything", "tok")

    exc = exc_info.value
    assert exc.status_code == 500
    assert erp_client.unavailable_message(exc) == "Payroll service is degraded"


async def test_a_non_json_error_body_falls_back_cleanly(monkeypatch):
    """A proxy's HTML error page must not crash the parse or produce a
    nonsense 'message' — the generic sentence is right here."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(502, text="<html>502 Bad Gateway</html>")

    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_http",
                        httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    with pytest.raises(erp_client.ErpApiUnavailable) as exc_info:
        await erp_client._request("GET", "/api/v1/ai/anything", "tok")

    assert exc_info.value.status_code == 502
    assert erp_client.unavailable_message(exc_info.value) == erp_client.UNAVAILABLE_FALLBACK


# ── team attendance: the reported path ───────────────────────────────────────

async def test_team_attendance_403_is_returned_not_raised(monkeypatch):
    """team_attendance_summary_node has an `if http_status == 403` branch that
    was unreachable dead code: without allow_403_body the 403 raised first, and
    the manager was told the HR system was down."""
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(403, json={"message": "You can only view your own team."})

    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_http",
                        httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    result = await erp_client.get_team_attendance_summary("tok", date="2026-08-20")

    assert result["http_status"] == 403
    assert erp_client.extract_erp_message(result["body"]) == "You can only view your own team."


async def test_team_attendance_400_is_returned_not_raised(monkeypatch):
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(400, json={"message": "Invalid date supplied."})

    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_http",
                        httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    result = await erp_client.get_team_attendance_summary("tok", date="not-a-date")

    assert result["http_status"] == 400
    assert erp_client.extract_erp_message(result["body"]) == "Invalid date supplied."


async def test_team_attendance_still_passes_the_date_through(monkeypatch):
    """Guard against the flags change disturbing the date param."""
    seen = {}

    def handler(request: httpx.Request) -> httpx.Response:
        seen["url"] = str(request.url)
        return httpx.Response(200, json={"data": {"date": "2026-08-20"}})

    monkeypatch.setattr(erp_client, "ERP_API_URL", "http://erp.test")
    monkeypatch.setattr(erp_client, "_http",
                        httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: None)

    await erp_client.get_team_attendance_summary("tok", date="2026-08-20")
    assert "date=2026-08-20" in seen["url"]
