"""Native pagination tests for PowerPath test assignments."""

from __future__ import annotations

import pytest

from timeback_common import InputValidationError
from timeback_powerpath import TestAssignment as PowerPathTestAssignment
from timeback_powerpath.resources.test_assignments import (
    TestAssignmentsResource as PowerPathTestAssignmentsResource,
)


def _make_assignment(id: str) -> dict[str, object]:
    return {
        "sourcedId": id,
        "studentSourcedId": "student-1",
        "studentEmail": "student@example.com",
        "assignedByUserSourcedId": None,
        "subject": "Math",
        "grade": "3",
        "assignmentStatus": "assigned",
    }


class _MockPaths:
    base = "/powerpath"


class _MockTransport:
    def __init__(self, pages: list[dict[str, object]]):
        self._pages = pages
        self._call_count = 0
        self.requests: list[dict[str, object]] = []
        self.paths = _MockPaths()
        self.base_url = "https://example.test"

    async def get(self, path: str, *, params: dict[str, object] | None = None) -> dict[str, object]:
        self.requests.append({"path": path, "params": params or {}})
        if self._call_count >= len(self._pages):
            return {"testAssignments": []}
        response = self._pages[self._call_count]
        self._call_count += 1
        return response


@pytest.mark.asyncio
async def test_stream_respects_max_items() -> None:
    transport = _MockTransport(
        [{"testAssignments": [_make_assignment("a1"), _make_assignment("a2")]}]
    )
    resource = PowerPathTestAssignmentsResource(transport)  # type: ignore[arg-type]
    items = await resource.stream({"student": "student-1"}, max_items=1).to_list()
    assert len(items) == 1
    assert isinstance(items[0], PowerPathTestAssignment)


@pytest.mark.asyncio
async def test_stream_advances_offsets() -> None:
    transport = _MockTransport(
        [
            {"testAssignments": [_make_assignment("a1")]},
            {"testAssignments": [_make_assignment("a2")]},
        ]
    )
    resource = PowerPathTestAssignmentsResource(transport)  # type: ignore[arg-type]
    await resource.stream({"student": "student-1", "limit": 1}).to_list()
    offsets = [req["params"].get("offset", 0) for req in transport.requests]
    assert offsets[0] == 0
    assert offsets[1] == 1


@pytest.mark.asyncio
async def test_stream_validates_limit() -> None:
    transport = _MockTransport([])
    resource = PowerPathTestAssignmentsResource(transport)  # type: ignore[arg-type]
    with pytest.raises(InputValidationError):
        resource.stream({"student": "student-1", "limit": 3001})
