"""
Order view
"""

from django.core.exceptions import PermissionDenied
from rest_framework import viewsets

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


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

    def get_queryset(self):
        user = self.request.user
        if user.role == "market":
            try:
                market_instance = models.Market.objects.get(user_id=user.id)
                return models.Order.objects.filter(
                    market_id=market_instance.id
                )
            except models.Market.DoesNotExist:
                raise PermissionDenied("Bunday Market mavjud emas.")
        return models.Order.objects.all()

    def get_serializer_class(self):
        if self.request.method == "GET":
            return serializers.OrderSerializer
        else:
            return serializers.OrderCreateSerializer
