from django.conf import settings
from django.http import HttpResponseRedirect
from urllib.parse import urlparse


class PrimaryDomainRedirectMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # Parse the primary hostname from WEBSITE_URL
        self.primary_host = urlparse(settings.WEBSITE_URL).netloc

    def __call__(self, request):
        # Skip redirects in DEBUG mode
        if settings.DEBUG:
            return self.get_response(request)

        # Check if the host is different from the primary host
        if request.get_host() != self.primary_host:
            # Build the redirect URL
            scheme = "https"  # Always use HTTPS for redirects
            path = request.get_full_path()  # Includes query string
            redirect_url = f"{scheme}://{self.primary_host}{path}"

            # Use 301 permanent redirect
            response = HttpResponseRedirect(redirect_url)
            response.status_code = 301
            return response

        return self.get_response(request)
