"""Tests para hoppscotch_list_requests.

Deterministas: monkeypatchean requests.post. Verifican el camino ok (devuelve la
lista normalizada) y el de error (GraphQL errors).
"""

import sys

import infra.hoppscotch_list_requests  # noqa: F401

# El __init__ rebinds el nombre a la funcion; recuperamos el submodulo real.
mod = sys.modules["infra.hoppscotch_list_requests"]


class _FakeResponse:
    def __init__(self, status_code=200, json_data=None):
        self.status_code = status_code
        self._json = json_data

    def json(self):
        if self._json is None:
            raise ValueError("no json")
        return self._json


def test_golden_lista_dos_requests(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["url"] = url
        captured["kwargs"] = kwargs
        return _FakeResponse(
            200,
            {
                "data": {
                    "requestsInCollection": [
                        {"id": "r1", "title": "Ping"},
                        {"id": "r2", "title": "Login"},
                    ]
                }
            },
        )

    monkeypatch.setattr(mod.requests, "post", fake_post)

    result = mod.hoppscotch_list_requests("col-1", access_token="ACCESS-JWT")

    assert result["status"] == "ok"
    assert result["requests"] == [
        {"id": "r1", "title": "Ping"},
        {"id": "r2", "title": "Login"},
    ]
    assert captured["url"].endswith("/graphql")
    assert captured["kwargs"]["cookies"] == {"access_token": "ACCESS-JWT"}
    assert "requestsInCollection" in captured["kwargs"]["json"]["query"]
    assert captured["kwargs"]["json"]["variables"] == {"c": "col-1", "t": 50}


def test_take_se_pasa_a_la_query(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["kwargs"] = kwargs
        return _FakeResponse(200, {"data": {"requestsInCollection": []}})

    monkeypatch.setattr(mod.requests, "post", fake_post)

    result = mod.hoppscotch_list_requests("col", access_token="A", take=10)
    assert result["status"] == "ok"
    assert result["requests"] == []
    assert captured["kwargs"]["json"]["variables"]["t"] == 10


def test_error_graphql_errors(monkeypatch):
    def fake_post(url, **kwargs):
        return _FakeResponse(
            200, {"errors": [{"message": "team_coll/not_found"}]}
        )

    monkeypatch.setattr(mod.requests, "post", fake_post)

    result = mod.hoppscotch_list_requests("bad", access_token="A")
    assert result["status"] == "error"
    assert result["error"] == "graphql errors"
    assert "errors" in result["data"]
