from django.conf import settings
from django.urls import resolve, reverse

class ReferrerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Check if the user is anonymous and going to the login page
        if not request.user.is_authenticated and request.path == reverse('login'):
            # Get the referring URL from the HTTP_REFERER header
            referrer = request.META.get('HTTP_REFERER')

            # Only store referrer if it exists and is not the login page itself
            if referrer and 'login' not in referrer:
                request.session['login_referrer'] = referrer

        response = self.get_response(request)
        return response
