# backend/apps/core/middleware.py

import logging

from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger(__name__)


class APIResponseMiddleware(MiddlewareMixin):
    """
    Middleware to ensure consistent API responses for Next.js
    """

    def process_response(self, request, response):
        # Only process API requests
        if not request.path.startswith("/api/"):
            return response

        # Ensure CORS headers are set
        if not response.has_header("Access-Control-Allow-Origin"):
            origin = request.META.get("HTTP_ORIGIN")

            # Allow localhost/127.0.0.1 (any port) and IPv6 loopback for development
            if origin:
                import re

                # support http or https, IPv4 and IPv6 loopback, any port
                localhost_pattern = r"^https?://(localhost|127\.0\.0\.1|\[::1\]):\d+"

                if re.match(localhost_pattern, origin):
                    response["Access-Control-Allow-Origin"] = origin
                    # Ensure caches vary by Origin
                    existing_vary = response.get("Vary")
                    if existing_vary:
                        response["Vary"] = f"{existing_vary}, Origin"
                    else:
                        response["Vary"] = "Origin"

                    # Helpful dev CORS headers (adjust for your frontend requests)
                    response["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
                    response["Access-Control-Allow-Headers"] = "Authorization, Content-Type, X-Requested-With"
                    # Uncomment if your dev frontend needs to send cookies/auth credentials
                    # response['Access-Control-Allow-Credentials'] = 'true'
                    logger.debug(f"Added CORS headers for origin: {origin}")
                else:
                    logger.warning(f"Rejected CORS request from origin: {origin}")
                    response["Access-Control-Allow-Origin"] = "null"

        return response
