from rest_framework import viewsets
from rest_framework.exceptions import PermissionDenied
from django.db.models import Q

class TenantViewSetMixin:
    """
    Mixin to filter querysets by organization and handle global data.
    """
    def get_queryset(self):
        queryset = super().get_queryset()
        organization = getattr(self.request, 'organization', None)
        has_is_global = hasattr(queryset.model, 'is_global')

        if not hasattr(queryset.model, 'organization'):
            if has_is_global:
                return queryset.filter(is_global=True)
            return queryset.none()

        # Staff with no org header = see everything; staff with org header = scoped to that org
        if getattr(self.request.user, 'is_staff', False) and not organization:
            return queryset

        scope = self.request.query_params.get('scope')
        if scope == 'own':
            if has_is_global:
                return queryset.filter(organization=organization, is_global=False)
            return queryset.filter(organization=organization)
        if scope == 'global':
            if has_is_global:
                return queryset.filter(is_global=True)
            return queryset.none()
        if scope == 'all' and not getattr(self.request.user, 'is_staff', False):
            # Non-staff cannot use scope=all, fall back to org+global
            scope = None

        if organization:
            if has_is_global:
                return queryset.filter(Q(organization=organization) | Q(is_global=True))
            return queryset.filter(organization=organization)

        if has_is_global:
            return queryset.filter(is_global=True)
        return queryset.none()

    def perform_create(self, serializer):
        model = serializer.Meta.model
        has_is_global = hasattr(model, 'is_global')
        has_organization = hasattr(model, 'organization')

        # Only superusers can explicitly set is_global to True
        if (
            has_is_global
            and serializer.validated_data.get('is_global') is True
            and not getattr(self.request.user, 'is_superuser', False)
        ):
            raise PermissionDenied("Only superusers can create global data.")
        
        organization = getattr(self.request, 'organization', None)
        save_kwargs = {}
        
        if organization and has_organization:
            save_kwargs['organization'] = organization
            # If creating for an organization, ensure it's not global unless superuser explicitly allowed it
            if has_is_global and 'is_global' not in save_kwargs:
                save_kwargs['is_global'] = False
        
        serializer.save(**save_kwargs)

    def perform_update(self, serializer):
        model = serializer.Meta.model
        has_is_global = hasattr(model, 'is_global')

        if has_is_global and not getattr(self.request.user, 'is_superuser', False):
            # 1. Prevent non-superusers from updating existing global records
            if getattr(serializer.instance, 'is_global', False):
                raise PermissionDenied("Only superusers can edit global data.")
            
            # 2. Prevent non-superusers from changing a record to global
            if serializer.validated_data.get('is_global') is True:
                raise PermissionDenied("Only superusers can promote data to global.")

        serializer.save()


