from django.db.models import Sum
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from core.apps.eggs.models import OrderItems, Product
from core.http.permissions import IsRole


class TopProductsView(APIView):
    permission_classes = [IsRole(["admin"]), IsAuthenticated]

    def get(self, request):
        top_products = (
            OrderItems.objects.filter(order_id__status__in=["done", "success"])
            .values("courier_product_id__group_id__product_id")
            .annotate(product_count=Sum("count"))
            .order_by("-product_count")
        )
        response_data = []
        for item in top_products:
            product = get_object_or_404(
                Product, id=item["courier_product_id__group_id__product_id"]
            )
            response_data.append(
                {
                    "product_name": product.name,
                    "product_count": item["product_count"],
                }
            )
        return Response(response_data)
