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

from .models import Caliber, CaliberStatus
from .serializers import CaliberListSerializer, CaliberSerializer


class CaliberViewSet(viewsets.ModelViewSet):
    queryset = Caliber.objects.select_related('submitted_by', 'reviewed_by')
    serializer_class = CaliberSerializer
    filterset_fields = ['status']
    search_fields = ['name', 'short_name']

    def get_permissions(self):
        if self.action in ('list', 'retrieve'):
            return [AllowAny()]
        if self.action in ('update', 'partial_update', 'destroy'):
            return [IsAdminUser()]
        return [IsAuthenticated()]

    def get_queryset(self):
        qs = super().get_queryset()
        user = self.request.user
        if user.is_authenticated:
            return qs.filter(
                Q(status=CaliberStatus.VERIFIED) |
                Q(status=CaliberStatus.PENDING, submitted_by=user)
            )
        return qs.filter(status=CaliberStatus.VERIFIED)

    def perform_create(self, serializer):
        serializer.save(
            status=CaliberStatus.PENDING,
            submitted_by=self.request.user,
        )

    @action(detail=True, methods=['post'], permission_classes=[IsAdminUser])
    def verify(self, request, pk=None):
        caliber = self.get_object()
        caliber.verify(request.user)
        return Response(self.get_serializer(caliber).data)

    @action(detail=True, methods=['post'], permission_classes=[IsAdminUser])
    def reject(self, request, pk=None):
        caliber = self.get_object()
        caliber.reject(request.user)
        return Response(self.get_serializer(caliber).data)
