from django.db.models import Q
from rest_framework import permissions, viewsets

from apps.core.permissions import IsOwnerOrReadOnly

from .models import ListItem, UserList
from .serializers import ListItemSerializer, UserListSerializer


class UserListViewSet(viewsets.ModelViewSet):
    serializer_class = UserListSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    lookup_field = "id"

    def get_queryset(self):
        # Users can see their own lists and public lists
        if self.request.user.is_authenticated:
            return UserList.objects.filter(Q(is_public=True) | Q(user=self.request.user))
        return UserList.objects.filter(is_public=True)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class ListItemViewSet(viewsets.ModelViewSet):
    serializer_class = ListItemSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
    lookup_field = "id"

    def get_queryset(self):
        return ListItem.objects.filter(user_list__is_public=True) | ListItem.objects.filter(
            user_list__user=self.request.user
        )
