from rest_framework import generics, permissions
from .models import Garment
from .serializers import GarmentSerializer
from common.response_helper import ResponseHelper


class GarmentListAPIView(generics.ListAPIView):
    """Public list of garments.

    Supports optional query parameters:
      - search: text search against garment name and description
      - category: category id or category name (partial match)
      - type: garment type (normal, premium, luxury)
    """
    serializer_class = GarmentSerializer
    permission_classes = [permissions.AllowAny]

    def get_queryset(self):
        qs = Garment.objects.filter(trash=False)
        search = self.request.query_params.get('search')
        category = self.request.query_params.get('category')
        garment_type = self.request.query_params.get('type')
        service = self.request.query_params.get('service')
        from django.db.models import Q

        if search:
            qs = qs.filter(Q(name__icontains=search) | Q(description__icontains=search))

        if category:
            # try numeric id first
            try:
                cat_id = int(category)
                from category.models import Category
                try:
                    cat_obj = Category.objects.get(id=cat_id)
                    # Include sub-categories
                    sub_cats = Category.objects.filter(parent=cat_obj)
                    cat_ids = [cat_id] + [c.id for c in sub_cats]
                    qs = qs.filter(category__id__in=cat_ids)
                except Category.DoesNotExist:
                    qs = qs.filter(category__id=cat_id)
            except (ValueError, TypeError):
                qs = qs.filter(category__name__icontains=category)

        if garment_type:
            qs = qs.filter(garment_type=garment_type)

        if service:
            try:
                service_id = int(service)
                # Filter garments that have the given service_id in their service_prices list
                # Using a list comprehension for compatibility with SQLite JSONField
                # We iterate over the current queryset to find matches
                valid_ids = []
                for garment in qs:
                    if isinstance(garment.service_prices, list):
                        for price_info in garment.service_prices:
                            if isinstance(price_info, dict) and price_info.get('service_id') == service_id:
                                valid_ids.append(garment.id)
                                break
                qs = qs.filter(id__in=valid_ids)
            except (ValueError, TypeError):
                pass

        return qs

    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='Garments list')

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


class GarmentDetailAPIView(generics.RetrieveAPIView):
    """Public garment detail endpoint."""
    queryset = Garment.objects.filter(trash=False)
    serializer_class = GarmentSerializer
    permission_classes = [permissions.AllowAny]

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