"""
Tests for the erp-api exchange capture on erp_api_call_logs
(services/erp_client.py::_request + _capture_payload/_redact).

Every outbound erp-api call already wrote a metadata row (method, endpoint,
status, latency). These cover the three payload columns added alongside it —
request_params, request_body, response_body — which record what was SENT to
erp-api and what came BACK, on the success path AND on each failure path,
where the response body is the thing nothing else keeps.

_log_call_background is stubbed with a collector rather than mocking the DB:
what matters here is the kwargs the log writer is handed, which is exactly
what becomes the row.
"""

import json

import pytest
import httpx

import services.erp_client as erp_client


@pytest.fixture
def logged(monkeypatch):
    """Collects every call-log row erp_client would have written."""
    rows = []
    monkeypatch.setattr(erp_client, "_log_call_background", lambda **kw: rows.append(kw))

    async def _persist(**kw):
        rows.append(kw)
    monkeypatch.setattr(erp_client, "_persist_call_log", _persist)
    monkeypatch.setattr(erp_client, "ERP_API_URL", "https://erp-api14.studyineurope.xyz")
    return rows


def fake_response(status_code=200, json_body=None, text=None):
    """A real httpx.Response, so .json()/.text behave exactly as they do live."""
    if json_body is not None:
        return httpx.Response(status_code=status_code, json=json_body,
                              request=httpx.Request("GET", "https://erp/x"))
    return httpx.Response(status_code=status_code, text=text or "",
                          request=httpx.Request("GET", "https://erp/x"))


def respond_with(monkeypatch, resp):
    async def _request(method, url, **kwargs):
        return resp
    monkeypatch.setattr(erp_client._http, "request", _request)


def raise_with(monkeypatch, exc):
    async def _request(method, url, **kwargs):
        raise exc
    monkeypatch.setattr(erp_client._http, "request", _request)


TEAM_SUMMARY = {
    "success": True,
    "data": {
        "type": "team_attendance_summary", "date": "2026-09-07", "scope": "direct_reports",
        "summary_cards": {"total_team": {"label": "Total Team", "value": 5}},
        "breakdown": {"attendance_recorded": 0, "not_recorded": 5, "off": 0},
        "missing_punch_details": {"employee_count": 0, "employees": []},
    },
}


class TestSuccessfulCallIsRecordedBothWays:

    async def test_request_params_and_response_body_land_on_the_row(self, monkeypatch, logged):
        respond_with(monkeypatch, fake_response(200, TEAM_SUMMARY))

        await erp_client.get_team_attendance_summary(
            "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
        )

        row = logged[-1]
        assert row["endpoint"] == "/api/v1/ai/attendance/summary"
        assert row["success"] is True
        # What we SENT — the date that selected the day.
        assert row["request_params"] == {"date": "2026-09-07"}
        assert row["request_body"] is None
        # What we RECEIVED — erp-api's body, verbatim.
        assert row["response_body"] == TEAM_SUMMARY
        assert row["response_body"]["data"]["breakdown"]["not_recorded"] == 5

    async def test_a_json_request_body_is_recorded_too(self, monkeypatch, logged):
        respond_with(monkeypatch, fake_response(200, {"success": True, "data": {"leave_request_id": 7}}))

        await erp_client.apply_leave(
            "caller-token", "casual", "2026-09-10", "2026-09-10",
            reason="Personal work", company_id=1, conversation_id="conv-1",
        )

        row = logged[-1]
        assert row["method"] == "POST"
        assert row["request_body"]["leave_type_slug"] == "casual"
        assert row["request_body"]["from_date"] == "2026-09-10"
        assert row["request_body"]["reason"] == "Personal work"
        assert row["response_body"]["data"]["leave_request_id"] == 7

    async def test_the_forwarded_caller_token_is_never_on_the_row(self, monkeypatch, logged):
        respond_with(monkeypatch, fake_response(200, TEAM_SUMMARY))

        await erp_client.get_team_attendance_summary(
            "super-secret-jwt", company_id=1, conversation_id="conv-1", date="2026-09-07",
        )

        assert "super-secret-jwt" not in json.dumps(logged[-1], default=str)


class TestFailurePathsKeepTheBody:
    """erp-api's own error body is the most useful thing to read back, so it
    has to survive the call.

    It now survives in two places: on the log row (always) and on the
    exception itself (ErpApiUnavailable.body / .erp_message), so a node can
    tell the user what erp-api actually said instead of "I'm unable to reach
    the HR system right now". Routes that opt into a business-error body don't
    raise at all — the body comes back as data."""

    async def test_403_business_message_is_returned_and_recorded(self, monkeypatch, logged):
        """get_team_attendance_summary opts into allow_403_body, so erp-api's
        refusal is DATA the node can read out, not an exception that gets
        flattened into an infrastructure error.

        `success` is True on the row on purpose: erp-api was reached and
        answered. The business outcome is carried by http_status/response_body.
        """
        body = {"success": False, "message": "I cannot retrieve information for other employees."}
        respond_with(monkeypatch, fake_response(403, body))

        result = await erp_client.get_team_attendance_summary(
            "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
        )

        assert result["http_status"] == 403
        assert result["body"] == body
        assert (erp_client.extract_erp_message(result["body"])
                == "I cannot retrieve information for other employees.")

        row = logged[-1]
        assert row["http_status"] == 403
        assert row["response_body"] == body
        assert row["request_params"] == {"date": "2026-09-07"}

    async def test_an_unexpected_status_still_raises_and_carries_the_body(self, monkeypatch, logged):
        """A route/status with no opt-in still raises — but the exception now
        carries erp-api's words, so the caller is not forced to invent them."""
        body = {"success": False, "message": "Attendance service is degraded."}
        respond_with(monkeypatch, fake_response(500, body))

        with pytest.raises(erp_client.ErpApiUnavailable) as exc_info:
            await erp_client.get_team_attendance_summary(
                "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
            )

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

        row = logged[-1]
        assert row["http_status"] == 500
        assert row["success"] is False
        assert row["response_body"] == body

    async def test_401_records_erp_apis_answer_not_the_token(self, monkeypatch, logged):
        respond_with(monkeypatch, fake_response(401, {"message": "Unauthenticated."}))

        with pytest.raises(erp_client.ErpApiUnauthorized):
            await erp_client.get_team_attendance_summary(
                "expired-token", company_id=1, conversation_id="conv-1",
            )

        row = logged[-1]
        assert row["error_code"] == "UNAUTHORIZED"
        assert row["response_body"] == {"message": "Unauthenticated."}
        assert "expired-token" not in json.dumps(row, default=str)

    async def test_a_non_json_body_is_recorded_as_raw_text(self, monkeypatch, logged):
        respond_with(monkeypatch, fake_response(200, text="<html>502 Bad Gateway</html>"))

        with pytest.raises(erp_client.ErpApiUnavailable):
            await erp_client.get_team_attendance_summary(
                "caller-token", company_id=1, conversation_id="conv-1",
            )

        assert logged[-1]["response_body"] == {"raw": "<html>502 Bad Gateway</html>"}

    async def test_a_timeout_still_records_what_we_asked_for(self, monkeypatch, logged):
        raise_with(monkeypatch, httpx.TimeoutException("timed out"))

        with pytest.raises(erp_client.ErpApiTimeout):
            await erp_client.get_team_attendance_summary(
                "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
            )

        row = logged[-1]
        assert row["error_code"] == "TIMEOUT"
        assert row["request_params"] == {"date": "2026-09-07"}
        # There was no response at all — the column must say so, not guess.
        assert row.get("response_body") is None

    async def test_an_unreachable_erp_api_still_records_what_we_asked_for(self, monkeypatch, logged):
        raise_with(monkeypatch, httpx.ConnectError("connection refused"))

        with pytest.raises(erp_client.ErpApiUnavailable):
            await erp_client.get_team_attendance_summary(
                "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
            )

        row = logged[-1]
        assert row["error_code"] == "UNAVAILABLE"
        assert row["request_params"] == {"date": "2026-09-07"}


class TestCaptureGuards:

    def test_credential_shaped_keys_are_redacted_at_any_depth(self):
        captured = erp_client._capture_payload({
            "employee_name": "Sameer Nair",
            "token": "abc123",
            "nested": {"access_token": "def456", "keep": "visible"},
            "rows": [{"password": "hunter2", "id": 1}],
        })

        assert captured["employee_name"] == "Sameer Nair"
        assert captured["token"] == "[redacted]"
        assert captured["nested"]["access_token"] == "[redacted]"
        assert captured["nested"]["keep"] == "visible"
        assert captured["rows"][0]["password"] == "[redacted]"
        assert captured["rows"][0]["id"] == 1

    def test_an_oversized_payload_is_previewed_not_dropped(self, monkeypatch):
        monkeypatch.setattr(erp_client, "_MAX_LOGGED_PAYLOAD_CHARS", 200)

        captured = erp_client._capture_payload({"employees": [{"name": "x" * 50}] * 20})

        assert captured["_truncated"] is True
        assert captured["_chars"] > 200
        assert len(captured["preview"]) == 200

    def test_an_unserializable_payload_is_marked_not_raised(self, monkeypatch):
        """default=str already absorbs dates/Decimals; this is the last
        resort, so an INSERT can never fail on a payload it was only
        supposed to observe."""
        class Circular(dict):
            def __init__(self):
                super().__init__()
                self["self"] = self

        captured = erp_client._capture_payload(Circular())
        assert "_unserializable" in captured

    def test_nothing_is_captured_when_the_switch_is_off(self, monkeypatch):
        monkeypatch.setattr(erp_client, "ERP_LOG_PAYLOADS", False)

        assert erp_client._capture_payload({"date": "2026-09-07"}) is None
        assert erp_client._capture_text("<html/>") is None

    async def test_the_metadata_row_is_still_written_with_the_switch_off(self, monkeypatch, logged):
        monkeypatch.setattr(erp_client, "ERP_LOG_PAYLOADS", False)
        respond_with(monkeypatch, fake_response(200, TEAM_SUMMARY))

        await erp_client.get_team_attendance_summary(
            "caller-token", company_id=1, conversation_id="conv-1", date="2026-09-07",
        )

        row = logged[-1]
        assert row["endpoint"] == "/api/v1/ai/attendance/summary"
        assert row["http_status"] == 200
        assert row["success"] is True
        assert row["request_params"] is None
        assert row["response_body"] is None
