from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response


class Pagination(PageNumberPagination):
    page_size = 20
    page_query_param = "page"
    page_size_query_param = "page_size"
    max_page_size = 100

    # ------------------------
    # 统一取参数（核心）
    # ------------------------
    def _get_param(self, request, key):
        return request.query_params.get(key) or request.data.get(key)

    # ------------------------
    # 页码
    # ------------------------
    def get_page_number(self, request, paginator):
        page = self._get_param(request, self.page_query_param)

        try:
            page = int(page)
            return max(page, 1)
        except (TypeError, ValueError):
            return 1

    # ------------------------
    # 每页数量
    # ------------------------
    def get_page_size(self, request):
        page_size = self._get_param(request, self.page_size_query_param)

        try:
            page_size = int(page_size)
            return min(max(page_size, 1), self.max_page_size)
        except (TypeError, ValueError):
            return self.page_size

    # ------------------------
    # 返回结构
    # ------------------------
    def get_paginated_response(self, data):
        return Response({
            "total": self.page.paginator.count,
            "page": self.page.number,
            "page_size": self.get_page_size(self.request),
            "total_pages": self.page.paginator.num_pages,
            "items": data,
        })