from rest_framework import generics, permissions
from .models import ServiceRequest
from .serializers import ServiceRequestSerializer
from common.response_helper import ResponseHelper

class ServiceRequestListCreateAPIView(generics.ListCreateAPIView):
    serializer_class = ServiceRequestSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return ServiceRequest.objects.filter(user=self.request.user, trash=False)

    def list(self, request, *args, **kwargs):
        qs = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(qs)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            paginated = self.get_paginated_response(serializer.data)
            return ResponseHelper.success(data=paginated.data, message='Service requests list')

        serializer = self.get_serializer(qs, many=True)
        return ResponseHelper.success(data=serializer.data, message='Service requests list')

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            return ResponseHelper.success(data=serializer.data, message='Service request created successfully', status=201)
        return ResponseHelper.validation_error(errors=serializer.errors)

class ServiceRequestDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = ServiceRequestSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return ServiceRequest.objects.filter(user=self.request.user, trash=False)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return ResponseHelper.success(data=serializer.data, message='Service request detail')

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid():
            self.perform_update(serializer)
            return ResponseHelper.success(data=serializer.data, message='Service request updated')
        return ResponseHelper.validation_error(errors=serializer.errors)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return ResponseHelper.success(message='Service request deleted successfully')
    
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.trash = True
        instance.save()
        return ResponseHelper.success(message='Service request deleted')
