# home/api/pagination.py

from django.core.paginator import Paginator, EmptyPage


def paginate_queryset(queryset, request, default_size=10, max_size=50):
    """
    Pagination helper untuk API JSON
    """
    try:
        page = int(request.GET.get("page", 1))
    except ValueError:
        page = 1

    try:
        page_size = int(request.GET.get("page_size", default_size))
    except ValueError:
        page_size = default_size

    page_size = min(page_size, max_size)

    paginator = Paginator(queryset, page_size)

    try:
        page_obj = paginator.page(page)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)

    meta = {
        "page": page_obj.number,
        "page_size": page_size,
        "total_items": paginator.count,
        "total_pages": paginator.num_pages,
    }

    return meta, page_obj.object_list