from rest_framework.request import Request
from rest_framework.mixins import (
    ListModelMixin,
    UpdateModelMixin,
    DestroyModelMixin,
)
from saas_base.drf.views import TenantEndpoint
from saas_base.drf.decorators import resource_permission
from saas_base.drf.filters import TenantIdFilter, IncludeFilter, ChoiceFilter
from saas_base.serializers.member import (
    MemberSerializer,
    MemberUpdateSerializer,
)
from saas_base.models import Member

__all__ = [
    'MemberListEndpoint',
    'MemberItemEndpoint',
]


class MemberListEndpoint(ListModelMixin, TenantEndpoint):
    serializer_class = MemberSerializer
    filter_backends = [TenantIdFilter, IncludeFilter]
    queryset = Member.objects.all()

    include_select_related_fields = ['user']
    include_prefetch_related_fields = ['groups']

    @resource_permission('iam.member.view')
    def get(self, request: Request, *args, **kwargs):
        """List all members in the tenant."""
        return self.list(request, *args, **kwargs)


class MemberItemEndpoint(UpdateModelMixin, DestroyModelMixin, TenantEndpoint):
    serializer_class = MemberUpdateSerializer
    queryset = Member.objects.all()

    @resource_permission('iam.member.manage')
    def patch(self, request: Request, *args, **kwargs):
        """Update a member's permissions and groups."""
        return self.partial_update(request, *args, **kwargs)

    @resource_permission('iam.member.manage')
    def delete(self, request: Request, *args, **kwargs):
        """Remove a member from the tenant."""
        # TODO: prevent removing owner
        return self.destroy(request, *args, **kwargs)
