# tenants/views.py
from rest_framework import viewsets, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from rest_framework.response import Response

from django.core.exceptions import ObjectDoesNotExist

from users.permissions import IsAuthorizedTenant
from .models import Tenants
from .serializers import TenantSerializer


class TenantViewSet(viewsets.ModelViewSet):
    serializer_class = TenantSerializer
    permission_classes = [IsAuthenticated, IsAuthorizedTenant]

    def get_queryset(self):
        user = self.request.user

        if user.is_superuser:
            return Tenants.objects.all()

        # If the user has Citizen role, show all tenants
        has_citizen_role = user.user_roles_set.filter(
            role__role_name="Citizen"
        ).exists()
        if has_citizen_role:
            return Tenants.objects.all()

        # Regular officer: show their tenant + all children
        try:
            user_tenant = user.user_roles_set.first().tenant
            return user_tenant.get_descendants(include_self=True)
        except (AttributeError, ObjectDoesNotExist):
            return Tenants.objects.none()

    @action(detail=True, methods=["get"])
    def with_children(self, request, pk=None):
        """
        Returns the tenant and all its descendant tenants (children, grandchildren, etc.).
        """
        try:
            tenant = Tenants.objects.get(pk=pk)
            descendants = tenant.get_descendants(include_self=True)
            print(descendants)
            serializer = self.get_serializer(descendants, many=True)
            return Response(serializer.data)
        except Tenants.DoesNotExist:
            return Response(
                {"error": "Tenant not found."}, status=status.HTTP_404_NOT_FOUND
            )
