from rest_framework import generics, status, permissions
from rest_framework.response import Response

from core.apps.eggs.models import AdditionalCost
from core.apps.eggs.serializers import AdditionalCostSerializer


class AdditionalCostView(generics.GenericAPIView):
    queryset = AdditionalCost.objects.all()
    serializer_class = AdditionalCostSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(
            {
                "message": "Qo'shimcha xarajat muvaffaqiyatli kiritildi.",
                "data": serializer.data,
            },
            status=status.HTTP_201_CREATED,
        )


# from collections import defaultdict
# from datetime import datetime
# from rest_framework import generics, status, permissions
# from rest_framework.response import Response
#
# from core.apps.eggs.models import AdditionalCost
# from core.apps.eggs.serializers import AdditionalCostSerializer
#
#
# class AdditionalCostView(generics.GenericAPIView):
#     queryset = AdditionalCost.objects.all()
#     serializer_class = AdditionalCostSerializer
#     permission_classes = [permissions.IsAuthenticated]
#
#     def get(self, request, *args, **kwargs):
#         queryset = self.get_queryset()
#         grouped_data = defaultdict(lambda: {"total_price": 0, "additional_costs": []})
#
#         for cost in queryset:
#             month_year = cost.created_at.strftime("%m-%Y")
#             grouped_data[month_year]["total_price"] += cost.price
#             grouped_data[month_year]["additional_costs"].append(cost)
#
#         response_data = []
#         for month_year, data in grouped_data.items():
#             month, year = month_year.split("-")
#             response_data.append({
#                 "month": month,
#                 "year": year,
#                 "total_price": data["total_price"],
#                 "additional_costs": AdditionalCostSerializer(data["additional_costs"], many=True).data
#             })
#
#         return Response(response_data)
#
#     def post(self, request, *args, **kwargs):
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         serializer.save()
#         return Response(
#             {
#                 "message": "Qo'shimcha xarajat muvaffaqiyatli kiritildi.",
#                 "data": serializer.data,
#             },
#             status=status.HTTP_201_CREATED,
#         )
