from django.utils.deprecation import MiddlewareMixin

class DocumentBranchMiddleware(MiddlewareMixin):
    """Middleware to ensure documents and notifications are properly filtered by branch"""
    
    def process_request(self, request):
        if not request.user.is_authenticated:
            return None
            
        # For superusers, ensure they can see all documents and notifications
        if request.user.is_superuser:
            # Handle document paths
            if request.path.startswith('/documents/'):
                # Temporarily clear selected_branch_id to show all documents
                if 'selected_branch_id' in request.session:
                    request.session['previous_branch_id'] = request.session['selected_branch_id']
                    del request.session['selected_branch_id']
            # Handle notification API paths
            elif request.path.startswith('/utils/api/notifications/'):
                # Temporarily clear selected_branch_id to show all notifications
                if 'selected_branch_id' in request.session:
                    request.session['previous_branch_id'] = request.session['selected_branch_id']
                    del request.session['selected_branch_id']
            # Handle main notifications page - respect branch selection
            elif request.path.startswith('/utils/notifications/'):
                # Don't interfere with branch selection for main notifications page
                pass
            # Restore previous branch selection when leaving documents/notifications pages
            elif 'previous_branch_id' in request.session:
                request.session['selected_branch_id'] = request.session['previous_branch_id']
                del request.session['previous_branch_id']
                
        return None