"""
Party view
"""

from django.db.models import Q
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

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


class PartViewSet(viewsets.ModelViewSet):
    queryset = models.Party.objects.all()
    http_method_names = ["get", "post", "put", "patch", "delete"]
    permission_classes = [IsAuthenticated, IsRole(["admin", "sklad", "courier"])]

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

    @action(detail=False, methods=["get"])
    def search(self, request):
        search_query = request.query_params.get("query", "")
        results = self.queryset.filter(
            Q(user_id__username__icontains=search_query)
            | Q(count__icontains=search_query)
            | Q(price__icontains=search_query)
            | Q(sold__icontains=search_query)
            | Q(sold_price__icontains=search_query)
            | Q(invoices__name__icontains=search_query)
            | Q(groups__product_id__name__icontains=search_query)
            | Q(groups__entry_price__icontains=search_query)
            | Q(groups__unit_price__icontains=search_query)
            | Q(groups__wholesale_price__icontains=search_query)
            | Q(groups__quantity__icontains=search_query)
            | Q(groups__broken_eggs__icontains=search_query)
        ).distinct()
        serializer = self.get_serializer(results, many=True)
        return Response()
