from django.db.models import CharField
from django.db.models.functions import Cast
from rest_framework import viewsets, permissions
from rest_framework.response import Response

from webservice_running.models import PreferredProviders
from webservice_running.serializer import PreferredProvidersSerializer


class PreferredProvidersMVS(viewsets.ModelViewSet):
    queryset = PreferredProviders.objects.all()
    serializer_class = PreferredProvidersSerializer
    permission_classes = [
        permissions.IsAuthenticated
    ]

    def list(self, request, *args, **kwargs):
        client = self.request.query_params.get('client')
        queryset = PreferredProviders.objects.all()
        if client is not None:
            queryset = queryset \
                .annotate(client_int=Cast('client', output_field=CharField())) \
                .filter(client_int=client)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def delete(self, request, *args, **kwargs):
        client = self.request.query_params.get('client')
        queryset = PreferredProviders.objects.all()
        if not client:
            return Response(
                {'error': 'client parameter is required'},
                status=status.HTTP_400_BAD_REQUEST
            )

        queryset = queryset \
            .annotate(client_int=Cast('client', output_field=CharField())) \
            .filter(client_int=client)
        queryset.delete()

        return Response(
            {'message': f'Objects with client {client} were deleted'},
            status=status.HTTP_204_NO_CONTENT
        )
