"""
CSRF Exemption Middleware
Exempts CSRF checks for specific public API endpoints that don't require authentication.
"""

from django.utils.deprecation import MiddlewareMixin
import re


class CSRFExemptMiddleware(MiddlewareMixin):
    """
    Middleware to exempt CSRF for public API endpoints.
    Runs before CSRF middleware to set the exemption flag.
    """
    
    # Paths that should be exempt from CSRF (public endpoints)
    # Patterns match both with and without trailing slashes
    EXEMPT_PATHS = [
        r'^/api/contact/submissions/?$',  # Contact form submission
        r'^/api/career/applications/?$',  # Job application submission (if needed)
        r'^/api/support/tickets/?$',      # Support ticket creation (if needed)
    ]
    
    def process_request(self, request):
        """
        Set CSRF exemption flag for matching paths.
        """
        if request.method == 'POST':
            path = request.path
            for pattern in self.EXEMPT_PATHS:
                if re.match(pattern, path):
                    # Set flag to bypass CSRF check
                    setattr(request, '_dont_enforce_csrf_checks', True)
                    break
        
        return None

