from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from apps.products.filters import ProductFilter
from apps.products.models import Product
from apps.products.serializers import ProductSerializer


class ProductViewSet(viewsets.ViewSet):
    """ViewSet for products."""

    permission_classes = [AllowAny]

    def list(self, request):
        """GET /products/ — list products with filtering."""
        qs = Product.objects.select_related("store", "category").all()
        filterset = ProductFilter(request.query_params, queryset=qs)
        if filterset.is_valid():
            qs = filterset.qs

        # Ordering
        ordering = request.query_params.get("ordering", "-created_at")
        allowed_ordering = ["price", "-price", "discount_percent", "-discount_percent",
                           "created_at", "-created_at"]
        if ordering in allowed_ordering:
            qs = qs.order_by(ordering)

        serializer = ProductSerializer(qs, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        """GET /products/{id}/ — product detail."""
        try:
            product = Product.objects.select_related("store", "category").get(pk=pk)
        except Product.DoesNotExist:
            return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
        serializer = ProductSerializer(product)
        return Response(serializer.data)

    @action(detail=False, methods=["get"], url_path="great-offers")
    def great_offers(self, request):
        """GET /products/great-offers/ — products with discounts."""
        offers = Product.objects.filter(discount_percent__gt=0).order_by("-discount_percent")
        serializer = ProductSerializer(offers, many=True)
        return Response(serializer.data)
