from rest_framework.exceptions import PermissionDenied


def get_current_team(user):
    membership = user.team_memberships.filter(status="active").select_related("team").first()
    if not membership:
        raise PermissionDenied("current user has no active team")
    return membership.team


class TeamScopedViewSetMixin:
    team_field = "team"

    def get_team(self):
        return get_current_team(self.request.user)

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(**{self.team_field: self.get_team()})

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

