from rest_framework import viewsets, permissions, filters
from rest_framework.views import APIView
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q
from core.models import Bookmark, Team
from core.serializers import BookmarkSerializer, BookmarkDetailSerializer, TeamSerializer
from core.tasks import process_bookmark

class ApiStatusView(APIView):
    permission_classes = [permissions.AllowAny]

    def get(self, request):
        return Response({
            "status": "up",
            "authenticated": request.user.is_authenticated
        })

class BookmarkViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['is_favorite']
    search_fields = ['title', 'url', 'notes', 'extraction__content_text']
    ordering_fields = ['created_at', 'updated_at', 'title']
    ordering = ['-created_at']

    def get_queryset(self):
        user_teams = self.request.user.teams.all()
        return Bookmark.objects.filter(
            Q(user=self.request.user) | 
            Q(shares__team__in=user_teams)
        ).distinct().select_related('extraction', 'summary')

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return BookmarkDetailSerializer
        return BookmarkSerializer

    def perform_create(self, serializer):
        bookmark = serializer.save()
        process_bookmark.delay(bookmark.id)

class TeamViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = TeamSerializer

    def get_queryset(self):
        return self.request.user.teams.all()
