import pytest

from gaiia.pagination import extract_connection, iter_nodes


def _conn(nodes, has_next=False, end="cur"):
    return {
        "nodes": nodes,
        "pageInfo": {"hasNextPage": has_next, "endCursor": end if has_next else None},
    }


def test_extract_connection_walks_dotted_path():
    data = {"a": {"b": _conn([1, 2])}}
    conn = extract_connection(data, "a.b")
    assert conn["nodes"] == [1, 2]


def test_extract_connection_missing_path_raises():
    with pytest.raises(KeyError):
        extract_connection({"a": {}}, "a.b")


def test_iter_nodes_terminates_on_last_page():
    pages = [
        {"things": _conn(["a", "b"], has_next=True, end="x")},
        {"things": _conn(["c"], has_next=False)},
    ]
    calls = []

    def fetch(cursor):
        calls.append(cursor)
        return pages.pop(0)

    assert list(iter_nodes(fetch, "things")) == ["a", "b", "c"]
    assert calls == [None, "x"]


def test_iter_nodes_handles_empty():
    def fetch(cursor):
        return {"things": _conn([])}

    assert list(iter_nodes(fetch, "things")) == []
