"""
Request ID Middleware
Generates unique request ID for every request and includes it in response headers
"""
import uuid
import logging
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger(__name__)


class RequestIDMiddleware(MiddlewareMixin):
    """
    Middleware that generates a unique request ID for every request
    and includes it in response headers as X-Request-ID
    """
    
    def process_request(self, request):
        """Generate or retrieve request ID"""
        # Check if request ID already exists in headers
        request_id = request.META.get('HTTP_X_REQUEST_ID') or request.META.get('X-Request-ID')
        
        if not request_id:
            # Generate new request ID
            request_id = str(uuid.uuid4())
        
        # Store in request for use in views/exception handlers
        request.request_id = request_id
        
        return None
    
    def process_response(self, request, response):
        """Add request ID to response headers"""
        # Get request ID from request
        request_id = getattr(request, 'request_id', None)
        
        if request_id:
            # Add to response headers
            response['X-Request-ID'] = request_id
        
        return response


