"""Tests para hoppscotch_create_request.

Deterministas: monkeypatchean requests.post para no tocar la red. Verifican que
el POST GraphQL lleva la mutation createRequestInCollection, el access_token en
la cookie, y que `request` es el json string de un HoppRESTRequest v:"2".
"""

import json
import sys

import infra.hoppscotch_create_request  # noqa: F401

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


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_crea_request_y_devuelve_id(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["url"] = url
        captured["kwargs"] = kwargs
        return _FakeResponse(
            200,
            {
                "data": {
                    "createRequestInCollection": {
                        "id": "req-99",
                        "title": "Ping",
                    }
                }
            },
        )

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

    result = mod.hoppscotch_create_request(
        "col-1",
        "GET",
        "https://api.example.com/ping",
        title="Ping",
        headers={"Accept": "application/json"},
        access_token="ACCESS-JWT",
    )

    assert result["status"] == "ok"
    assert result["id"] == "req-99"
    assert result["title"] == "Ping"

    # El POST fue al endpoint GraphQL con la cookie access_token.
    assert captured["url"].endswith("/graphql")
    assert captured["kwargs"]["cookies"] == {"access_token": "ACCESS-JWT"}

    payload = captured["kwargs"]["json"]
    assert "createRequestInCollection" in payload["query"]
    variables = payload["variables"]
    assert variables["c"] == "col-1"
    assert variables["d"]["title"] == "Ping"

    # `request` es un json string de un HoppRESTRequest v:"2".
    req = json.loads(variables["d"]["request"])
    assert req["v"] == "2"
    assert req["method"] == "GET"
    assert req["endpoint"] == "https://api.example.com/ping"
    assert req["name"] == "Ping"


def test_body_json_se_serializa_en_el_request(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["kwargs"] = kwargs
        return _FakeResponse(
            200,
            {"data": {"createRequestInCollection": {"id": "r", "title": "t"}}},
        )

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

    mod.hoppscotch_create_request(
        "col-2",
        "POST",
        "https://api.example.com/login",
        body='{"user":"neo"}',
        body_type="json",
        access_token="A",
    )

    req = json.loads(captured["kwargs"]["json"]["variables"]["d"]["request"])
    assert req["method"] == "POST"
    assert req["body"] == {
        "contentType": "application/json",
        "body": '{"user":"neo"}',
    }


def test_team_id_se_incluye_en_data(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["kwargs"] = kwargs
        return _FakeResponse(
            200,
            {"data": {"createRequestInCollection": {"id": "r", "title": "t"}}},
        )

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

    mod.hoppscotch_create_request(
        "col-3",
        "GET",
        "https://api.example.com/x",
        team_id="team-abc",
        access_token="A",
    )

    data = captured["kwargs"]["json"]["variables"]["d"]
    assert data["teamID"] == "team-abc"


def test_team_id_omitido_no_aparece_en_data(monkeypatch):
    captured = {}

    def fake_post(url, **kwargs):
        captured["kwargs"] = kwargs
        return _FakeResponse(
            200,
            {"data": {"createRequestInCollection": {"id": "r", "title": "t"}}},
        )

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

    mod.hoppscotch_create_request(
        "col-4", "GET", "https://api.example.com/x", access_token="A"
    )

    data = captured["kwargs"]["json"]["variables"]["d"]
    assert "teamID" not in data


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

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

    result = mod.hoppscotch_create_request(
        "bad", "GET", "https://x", access_token="A"
    )
    assert result["status"] == "error"
    assert result["error"] == "graphql errors"
    assert "errors" in result["data"]
