from django.db.models import Q

from rest_framework.viewsets import ModelViewSet

from ichec_django_core.models import Organization

from ichec_django_core.serializers import (
    OrganizationDetailSerializer,
    OrganizationPublicDetailSerializer,
    OrganizationListSerializer,
)

from .core import SearchableModelViewSet
from .permissions import PublicViewMemberEditOrDjangoModelPermissions


class OrganizationViewSet(SearchableModelViewSet):

    model = Organization
    queryset = Organization.objects.filter(active=True)
    serializer_class = OrganizationListSerializer
    permission_classes = [
        PublicViewMemberEditOrDjangoModelPermissions,
    ]
    ordering_fields = SearchableModelViewSet.ordering_fields + ("name",)
    ordering: tuple[str, ...] = ("name",)
    search_fields = ["name", "address__line1", "address__country", "address__region"]
    filterset_fields = ("members__id",)

    serializers = {
        "retrieve": OrganizationDetailSerializer,
        "public_retrieve": OrganizationPublicDetailSerializer,
        "list": OrganizationListSerializer,
        "create": OrganizationDetailSerializer,
        "update": OrganizationDetailSerializer,
        "partial_update": OrganizationDetailSerializer,
    }

    def get_queryset(self):
        """
        Public users can only see public Orgs
        Registered users can see pubic Orgs or orgs they are members of
        Users with view permission can see all Orgs
        """

        queryset = ModelViewSet.get_queryset(self)

        if not self.request.user.is_authenticated:
            return queryset.filter(public=True)

        if self.has_model_view_permission():
            return queryset

        return queryset.filter(
            Q(public=True) | Q(members__id=self.request.user.id)
        ).distinct()
