
import uuid
from django.utils.deprecation import MiddlewareMixin
from users.models import Branch

class BranchFilteringMiddleware(MiddlewareMixin):
    """
    Middleware to ensure branch filtering context is available in all requests
    """
    
    def process_request(self, request):
        if request.user.is_authenticated:
            # Ensure selected_branch_id is in session
            if 'selected_branch_id' not in request.session:
                if hasattr(request.user, 'branch') and request.user.branch:
                    request.session['selected_branch_id'] = str(request.user.branch.id)
                else:
                    # Set to main branch as fallback
                    main_branch = Branch.objects.filter(is_main=True).first()
                    if main_branch:
                        request.session['selected_branch_id'] = str(main_branch.id)
            
            # Validate selected_branch_id is a proper UUID — clear stale name strings
            selected_branch_id = request.session.get('selected_branch_id')
            if selected_branch_id:
                try:
                    uuid.UUID(str(selected_branch_id))
                except (ValueError, AttributeError):
                    # Not a valid UUID (e.g. old session stored branch name) — clear it
                    request.session['selected_branch_id'] = None
                    request.session.modified = True
                    selected_branch_id = None

            # Make branch available in request
            if selected_branch_id:
                try:
                    request.selected_branch = Branch.objects.get(id=selected_branch_id)
                except Branch.DoesNotExist:
                    request.selected_branch = None
            else:
                request.selected_branch = None
        
        return None
    
    def process_template_response(self, request, response):
        """Add branch context to template responses"""
        if hasattr(response, 'context_data') and response.context_data is not None:
            if hasattr(request, 'selected_branch'):
                response.context_data['selected_branch'] = request.selected_branch
                response.context_data['selected_branch_id'] = request.session.get('selected_branch_id')
        
        return response
