from django.contrib import messages
from django.contrib.auth import views as auth_views
from django.urls import reverse
from .forms import EmailOrUsernameAuthenticationForm

class CustomLoginView(auth_views.LoginView):
    template_name = 'registration/login.html'
    authentication_form = EmailOrUsernameAuthenticationForm

    def get_success_url(self):
        # First check the 'next' parameter which has higher priority
        next_url = self.request.POST.get('next') or self.request.GET.get('next')

        # Check if the next URL is a password reset page and avoid that redirect
        if next_url and next_url.strip():
            # Avoid redirecting to password reset pages after login
            if 'reset' in next_url or 'password_reset' in next_url:
                # Redirect to profile or index instead
                return reverse('profile')
            return next_url

        # Then check if we have a stored referrer URL
        referrer = self.request.session.get('login_referrer')
        if referrer:
            # Avoid redirecting to password reset pages from stored referrer
            if 'reset' not in referrer and 'password_reset' not in referrer:
                # Clear the stored referrer to prevent reuse
                del self.request.session['login_referrer']
                return referrer

        # Fall back to default
        return reverse('index')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Check for inactive user in session
        inactive_user_email = self.request.session.get('inactive_user_email')
        if inactive_user_email:
            context['inactive_user_email'] = inactive_user_email
            context['show_resend_activation'] = True

        return context

    def get(self, request, *args, **kwargs):
        # Capture referrer for anonymous users (replaces middleware functionality)
        if not request.user.is_authenticated:
            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

        # Clear any potential password reset session data
        keys_to_clear = [key for key in request.session.keys()
                         if 'reset' in key or 'password' in key]
        for key in keys_to_clear:
            del request.session[key]

        # Clear inactive user session data on GET request (fresh login page)
        request.session.pop('inactive_user_email', None)
        request.session.pop('inactive_user_id', None)

        storage = messages.get_messages(request)
        for _ in storage:
            pass

        if len(storage._loaded_messages) == 1:
            del storage._loaded_messages[0]

        return super().get(request, *args, **kwargs)
