from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import Count
from .models import Notification
from .serializers import NotificationSerializer


class NotificationListView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        notifs = Notification.objects.filter(
            recipient=request.user
        ).select_related("sender")[:50]
        serializer = NotificationSerializer(
            notifs, many=True, context={"request": request}
        )
        unread = Notification.objects.filter(
            recipient=request.user, is_read=False
        ).count()
        return Response({
            "notifications": serializer.data,
            "unread_count":  unread,
        })


class NotificationMarkReadView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request, pk=None):
        if pk:
            # Mark single notification read
            Notification.objects.filter(
                pk=pk, recipient=request.user
            ).update(is_read=True)
        else:
            # Mark all read
            Notification.objects.filter(
                recipient=request.user, is_read=False
            ).update(is_read=True)
        unread = Notification.objects.filter(
            recipient=request.user, is_read=False
        ).count()
        return Response({"unread_count": unread})


class NotificationDeleteView(APIView):
    permission_classes = [IsAuthenticated]

    def delete(self, request, pk):
        Notification.objects.filter(pk=pk, recipient=request.user).delete()
        return Response(status=204)

    def post(self, request):
        """Delete all notifications"""
        Notification.objects.filter(recipient=request.user).delete()
        return Response(status=204)