"""
统一响应格式工具类
"""
from rest_framework.response import Response
from rest_framework import status


class APIResponse(Response):
    """
    统一API响应格式
    {
        "code": 0,           # 0表示成功，非0表示错误码
        "message": "success", # 响应消息
        "data": {}           # 响应数据
    }
    """
    
    def __init__(self, data=None, code=0, message='success', 
                 status_code=status.HTTP_200_OK, **kwargs):
        response_data = {
            'code': code,
            'message': message,
            'data': data
        }
        super().__init__(data=response_data, status=status_code, **kwargs)


def success(data=None, message='success'):
    """成功响应"""
    return APIResponse(data=data, code=0, message=message)


def error(code=1, message='error', status_code=status.HTTP_400_BAD_REQUEST, data=None):
    """错误响应"""
    return APIResponse(data=data, code=code, message=message, status_code=status_code)


def paginated_response(paginator, serializer_class, queryset, request):
    """分页响应"""
    page = paginator.paginate_queryset(queryset, request)
    if page is not None:
        serializer = serializer_class(page, many=True)
        return APIResponse(
            data={
                'total': paginator.page.paginator.count,
                'page': paginator.page.number,
                'page_size': paginator.page_size,
                'items': serializer.data
            }
        )
    serializer = serializer_class(queryset, many=True)
    return APIResponse(data={'items': serializer.data})
