from rest_framework import generics, permissions, status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.contenttypes.models import ContentType
from .models import Rating
from .serializers import RatingSerializer

class CreateRatingView(generics.CreateAPIView):
    serializer_class = RatingSerializer
    permission_classes = [permissions.IsAuthenticated]

    def perform_create(self, serializer):
        # Serializer'ın create metodunda user ve content_type işlemleri yapılıyor
        serializer.save()

class ListRatingsView(APIView):
    """
    Belirli bir model ve ID için yorumları listeler.
    Örn: /api/v1/reviews/list/?model=product&id=1
    """
    def get(self, request):
        model_name = request.query_params.get('model')
        object_id = request.query_params.get('id')

        if not model_name or not object_id:
            return Response({"error": "model ve id parametreleri gereklidir."}, status=status.HTTP_400_BAD_REQUEST)

        try:
            content_type = ContentType.objects.get(model=model_name.lower())
            ratings = Rating.objects.filter(content_type=content_type, object_id=object_id)
            serializer = RatingSerializer(ratings, many=True)
            return Response(serializer.data)
        except ContentType.DoesNotExist:
            return Response({"error": "Model bulunamadı."}, status=status.HTTP_404_NOT_FOUND)
