"""Tests for cursor-based pagination."""

import httpx

from duffelbag import Duffel
from duffelbag.models import Airline


def test_single_page(client, mock_transport):
    mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 2, "after": None},
            "data": [
                {"id": "arl_1", "name": "Airline One"},
                {"id": "arl_2", "name": "Airline Two"},
            ],
        })
    )

    airlines = list(client.airlines.list(limit=2))
    assert len(airlines) == 2
    assert airlines[0].id == "arl_1"
    assert airlines[1].name == "Airline Two"
    assert len(mock_transport.requests) == 1


def test_multi_page_iteration(client, mock_transport):
    # Page 1
    mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 1, "after": "cursor_abc"},
            "data": [{"id": "arl_1", "name": "First"}],
        })
    )
    # Page 2
    mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 1, "after": None},
            "data": [{"id": "arl_2", "name": "Second"}],
        })
    )

    airlines = list(client.airlines.list(limit=1))
    assert len(airlines) == 2
    assert airlines[0].id == "arl_1"
    assert airlines[1].id == "arl_2"

    # Second request should include after cursor
    assert "after=cursor_abc" in str(mock_transport.requests[1].url)


def test_page_method(client, mock_transport):
    mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 2, "after": "next"},
            "data": [{"id": "arl_1"}, {"id": "arl_2"}],
        })
    )

    iterator = client.airlines.list(limit=2)
    page = iterator.page()
    assert len(page) == 2
    assert isinstance(page[0], Airline)


def test_empty_response(client, mock_transport):
    mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 50, "after": None},
            "data": [],
        })
    )

    airlines = list(client.airlines.list())
    assert airlines == []
