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')
        if next_url and next_url.strip():
            return next_url

        # Then check if we have a stored referrer URL
        referrer = self.request.session.get('login_referrer')
        if 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(self, request, *args, **kwargs):
        messages.get_messages(request).used = True
        return super().get(request, *args, **kwargs)
