"""Pagination support for MCard collections."""

from dataclasses import dataclass
from typing import Generic, Optional, TypeVar

T = TypeVar("T")


@dataclass
class Page(Generic[T]):
    """A page of search results."""

    items: list[T]
    page_number: int
    page_size: int
    total_items: int
    total_pages: int
    has_next: bool
    has_previous: bool

    @classmethod
    def create(cls, items: list, total_items: int, page_number: int, page_size: int) -> "Page":
        """Factory that computes has_next, has_previous, and total_pages automatically."""
        total_pages = (total_items + page_size - 1) // page_size if page_size > 0 else 0
        return cls(
            items=items,
            total_items=total_items,
            page_number=page_number,
            page_size=page_size,
            total_pages=total_pages,
            has_next=total_items > page_number * page_size,
            has_previous=page_number > 1,
        )

    @property
    def next_page_number(self) -> Optional[int]:
        """Get the next page number, or None if this is the last page."""
        return self.page_number + 1 if self.has_next else None

    @property
    def previous_page_number(self) -> Optional[int]:
        """Get the previous page number, or None if this is the first page."""
        return self.page_number - 1 if self.has_previous else None
