# users/backends.py
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q

UserModel = get_user_model()

class CaseInsensitiveModelBackend(ModelBackend):
    def authenticate(self, request, username=None, email=None, password=None, **kwargs):
        # For Django admin login which uses username field
        if username is not None:
            username_or_email = username
        # For API/frontend login which might use email field directly
        elif email is not None:
            username_or_email = email
        else:
            return None

        try:
            # Case-insensitive lookup using lowercase comparison
            user = UserModel.objects.get(Q(email__iexact=username_or_email))
            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce timing
            # attacks targeting a particular user
            UserModel().set_password(password)
        except UserModel.MultipleObjectsReturned:
            # If multiple users found, get the first one (should be rare if emails unique)
            user = UserModel.objects.filter(Q(email__iexact=username_or_email)).first()
            if user.check_password(password):
                return user
            
        return None