
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib.auth.models import Group

class CustomerAccessMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        
    def __call__(self, request):
        response = self.get_response(request)
        return response
        
    def process_view(self, request, view_func, view_args, view_kwargs):
        # Define backend paths that customers shouldn't access
        backend_paths = [
            '/dashboard/', '/sales/', '/hr/', '/inventory/', 
            '/customers/', '/suppliers/', '/reports/', '/expenses/',
            '/orders/', '/settings/', '/auth/', '/admin/'
        ]
        
        # Check if user is trying to access backend
        if any(request.path.startswith(path) for path in backend_paths):
            if request.user.is_authenticated:
                # Check if user has any staff groups
                staff_groups = ['Sales', 'Supervisor', 'Manager', 'Administrator']
                user_groups = [group.name for group in request.user.groups.all()]
                
                # If user has no staff groups or is not staff, redirect to shop
                if not any(group in staff_groups for group in user_groups) and not request.user.is_staff:
                    return redirect('shop:product_list')
        
        return None
