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

from .models import Notification
from .serializers import NotificationSerializer


class NotificationViewSet(viewsets.ModelViewSet):
    """
    API endpoint for user notifications.
    Users can only see their own notifications.
    """
    serializer_class = NotificationSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Return notifications for the current user only."""
        return Notification.objects.filter(recipient=self.request.user)

    def list(self, request, *args, **kwargs):
        """List notifications with optional filtering."""
        queryset = self.get_queryset()

        # Filter by read status
        read_filter = request.query_params.get('read')
        if read_filter is not None:
            queryset = queryset.filter(read=read_filter.lower() == 'true')

        # Limit results (default 50)
        limit = int(request.query_params.get('limit', 50))
        queryset = queryset[:limit]

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def unread_count(self, request):
        """Get the count of unread notifications."""
        count = self.get_queryset().filter(read=False).count()
        return Response({'count': count})

    @action(detail=True, methods=['post'])
    def mark_read(self, request, pk=None):
        """Mark a single notification as read."""
        notification = self.get_object()
        notification.read = True
        notification.save(update_fields=['read'])
        return Response({'status': 'marked as read'})

    @action(detail=False, methods=['post'])
    def mark_all_read(self, request):
        """Mark all notifications as read for the current user."""
        updated = self.get_queryset().filter(read=False).update(read=True)
        return Response({'status': f'marked {updated} notifications as read'})

    @action(detail=False, methods=['delete'])
    def clear_all(self, request):
        """Delete all read notifications for the current user."""
        deleted, _ = self.get_queryset().filter(read=True).delete()
        return Response({'status': f'deleted {deleted} notifications'})
