# example_app/views.py

from rest_framework import mixins, viewsets
from rest_framework.permissions import IsAuthenticated

from .models import Organization, Project
from .serializers import OrganizationSerializer, ProjectSerializer


class OrganizationViewSet(
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet,
):
    serializer_class = OrganizationSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # Only return organizations the user has permission to view
        return Organization.get_queryset_for_user(
            self.request.user, "view_organization"
        )

    def perform_create(self, serializer):
        # Organizations are root nodes (no parent)
        serializer.save(parent=None)


class ProjectViewSet(
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    viewsets.GenericViewSet,
):
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        # Only return projects the user has permission to view
        return Project.get_queryset_for_user(self.request.user, "view_project")

    def perform_create(self, serializer):
        # Projects live under an organization
        org_id = self.request.data.get("organization_id")
        org = Organization.objects.get(restricted_object_id=org_id)
        serializer.save(parent=org)
