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

import httpx
import pytest

from duffelbag.models import Airline


async def test_async_single_page(async_client, async_mock_transport):
    async_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 = [a async for a in async_client.airlines.list(limit=2)]
    assert len(airlines) == 2
    assert airlines[0].id == "arl_1"
    assert airlines[1].name == "Airline Two"
    assert len(async_mock_transport.requests) == 1


async def test_async_multi_page_iteration(async_client, async_mock_transport):
    async_mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 1, "after": "cursor_abc"},
            "data": [{"id": "arl_1", "name": "First"}],
        })
    )
    async_mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 1, "after": None},
            "data": [{"id": "arl_2", "name": "Second"}],
        })
    )

    airlines = [a async for a in async_client.airlines.list(limit=1)]
    assert len(airlines) == 2
    assert airlines[0].id == "arl_1"
    assert airlines[1].id == "arl_2"
    assert "after=cursor_abc" in str(async_mock_transport.requests[1].url)


async def test_async_page_method(async_client, async_mock_transport):
    async_mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 2, "after": "next"},
            "data": [{"id": "arl_1"}, {"id": "arl_2"}],
        })
    )

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


async def test_async_empty_response(async_client, async_mock_transport):
    async_mock_transport.queue_response(
        httpx.Response(200, json={
            "meta": {"limit": 50, "after": None},
            "data": [],
        })
    )

    airlines = [a async for a in async_client.airlines.list()]
    assert airlines == []
