"""
Courier Product view
"""

from rest_framework import response, status, viewsets

from core.apps.eggs import models, serializers
from core.http.permissions import IsRole


class CourierProductViewSet(viewsets.ModelViewSet):
    http_method_names = ["get", "post", "put", "patch", "delete"]
    permission_classes = [IsRole(["courier"])]

    def get_queryset(self):
        user = self.request.user
        return models.CourierProduct.objects.filter(
            courier_id__user_id=user.id
        )

    def get_serializer_class(self):
        if self.request.method == "GET":
            return serializers.CourierProductSerializer
        return serializers.CourierProductReturnSerializer


class ReturnEggsViewSet(viewsets.ViewSet):
    permission_classes = [IsRole(["courier"])]

    def update(self, request, pk=None):
        courier_products = models.CourierProduct.objects.filter(
            courier_id__user_id=request.user.id
        )

        if not courier_products.exists():
            return response.Response(
                {"error": "No products found for this courier."},
                status=status.HTTP_404_NOT_FOUND,
            )

        for courier_product in courier_products:
            courier_product.group_id.quantity += courier_product.count
            courier_product.group_id.party_id.courier_eggs -= (
                courier_product.count
            )
            courier_product.group_id.party_id.remaining_count += (
                courier_product.count
            )
            courier_product.return_eggs = courier_product.count
            courier_product.count = 0
            courier_product.save()
            courier_product.group_id.save()
            courier_product.group_id.party_id.save()
            courier_product.delete()

        return response.Response(
            data={"status": "success"}, status=status.HTTP_200_OK
        )
