from rest_framework import generics, permissions, status
from django.db import models
from common.response_helper import ResponseHelper
from .models import BackToBase
from .serializers import BackToBaseSerializer
from django.utils import timezone
from rest_framework.views import APIView

class BackToBaseListCreateAPIView(generics.ListCreateAPIView):
    serializer_class = BackToBaseSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        qs = BackToBase.objects.all()
        
        # Filter by status (default: active/unresolved)
        status_filter = self.request.query_params.get('status', 'active')
        if status_filter == 'active':
            qs = qs.filter(is_resolved=False)
        elif status_filter == 'resolved':
            qs = qs.filter(is_resolved=True)
        
        if user.is_staff or user.is_superuser:
            return qs
        
        # Check if user is a rider
        try:
            if hasattr(user, 'rider_profile'):
                 return qs.filter(models.Q(rider=user.rider_profile) | models.Q(rider__isnull=True))
        except Exception:
            pass
        
        # Fallback for customer
        return qs.filter(customer=user)

    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='Back to Base list')

        serializer = self.get_serializer(qs, many=True)
        return ResponseHelper.success(data=serializer.data, message='Back to Base list')

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            instance = serializer.save()
            return ResponseHelper.success(data=self.get_serializer(instance).data, message='Back to Base entry created', status=status.HTTP_201_CREATED)
        return ResponseHelper.validation_error(errors=serializer.errors)



class BackToBaseDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    serializer_class = BackToBaseSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        user = self.request.user
        qs = BackToBase.objects.all()
        if user.is_staff or user.is_superuser:
            return qs
        try:
            if hasattr(user, 'rider_profile'):
                 return qs.filter(models.Q(rider=user.rider_profile) | models.Q(rider__isnull=True))
        except Exception:
            pass
        return qs.filter(customer=user)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return ResponseHelper.success(data=serializer.data, message='Back to Base 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():
            updated = serializer.save()
            return ResponseHelper.success(data=self.get_serializer(updated).data, message='Back to Base updated')
        return ResponseHelper.validation_error(errors=serializer.errors)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.delete()
        return ResponseHelper.success(message='Back to Base entry deleted', status=status.HTTP_204_NO_CONTENT)


class BackToBaseResolveAPIView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, pk):
        try:
            entry = BackToBase.objects.get(pk=pk)
        except BackToBase.DoesNotExist:
            return ResponseHelper.error(message='Entry not found', code=404)
        
        # Permission check (only staff or assigned rider?)
        # Assuming staff or the rider who created it (or is assigned) can resolve it?
        # Usually only staff resolves back to base issues.
        if not (request.user.is_staff or request.user.is_superuser):
             return ResponseHelper.error(message='Permission denied', code=403)

        if not entry.is_resolved:
            entry.is_resolved = True
            entry.resolved_at = timezone.now()
            entry.save()
            return ResponseHelper.success(message='Back to Base entry resolved')
        
        return ResponseHelper.success(message='Entry is already resolved')

