"""
Custom authentication backends for the recruitment system.
"""

from allauth.account.auth_backends import AuthenticationBackend
from django.shortcuts import redirect
from django.urls import reverse


class CustomAuthenticationBackend(AuthenticationBackend):
    """
    Custom authentication backend that extends django-allauth's AuthenticationBackend
    to handle user type-based redirection after successful login.
    """

    def post_login(self, request, user, **kwargs):
        """
        Called after successful authentication.
        Sets the appropriate redirect URL based on user type.
        """
        # Set redirect URL based on user type
        if user.user_type == 'staff':
            redirect_url = '/dashboard/'
        elif user.user_type == 'agency':
            redirect_url = reverse('agency_portal_dashboard')
        elif user.user_type == 'candidate':
            redirect_url = reverse('candidate_portal_dashboard')
        else:
            # Fallback to default redirect URL if user type is unknown
            redirect_url = '/'

        # Store the redirect URL in session for allauth to use
        request.session['allauth_login_redirect_url'] = redirect_url

        # Call the parent method to complete the login process
        return super().post_login(request, user, **kwargs)
