# companies/permissions.py
from functools import wraps
from django.shortcuts import redirect
from django.contrib import messages
from django.urls import reverse

def company_feature_required(feature_flag, message="Your subscription plan does not support this feature. Please contact support to upgrade."):
    """
    Decorator for views that checks if the company's subscription plan allows a feature.
    Superusers bypass this check.
    """
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated and request.user.is_superuser:
                return view_func(request, *args, **kwargs)
                
            company = getattr(request, 'company', None)
            if not company:
                return redirect('dashboard')
                
            plan = getattr(company, 'plan', None)
            
            # Check the boolean flag on the plan model
            if plan and getattr(plan, feature_flag, False):
                return view_func(request, *args, **kwargs)
                
            # If feature is disabled, block access
            messages.error(request, message)
            
            # We must return an HttpResponse. Redirect to dashboard.
            return redirect('dashboard')
            
        return _wrapped_view
    return decorator
