"""
Market view
"""

from rest_framework import viewsets

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


class MarketViewSet(viewsets.ModelViewSet):
    queryset = models.Market.objects.all()
    serializer_class = serializers.MarketSerializer
    http_method_names = ["get", "post", "put", "patch", "delete"]
    permission_classes = [IsRole(["sklad", "admin", "courier", "market"])]

    def get_queryset(self):
        user = self.request.user
        if user.role in ["admin", "sklad", "courier"]:
            return models.Market.objects.all()
        elif user.role == "market":
            return models.Market.objects.filter(user_id=user.id)
        return None


class MarketHistoryViewSet(viewsets.ModelViewSet):
    queryset = models.Market.objects.all()
    serializer_class = serializers.MarketHistorySerializer
    http_method_names = ["get"]
    permission_classes = [IsRole(["sklad", "admin", "courier", "market"])]

    def get_queryset(self):
        user = self.request.user
        if user.role in ["admin", "sklad", "courier"]:
            return models.Market.objects.all().order_by("-debts__created_at")
        elif user.role == "market":
            return models.Market.objects.filter(user_id=user.id).order_by("-debts__created_at")
        return None
    
