# backends.py
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
import logging

logger = logging.getLogger(__name__)

class EmailOrUsernameModelBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()

        print(f"Backend attempting authentication for: {username}")  # Debug print
        logger.info(f"Backend attempting authentication for: {username}")

        try:
            user = UserModel.objects.get(
                Q(username__iexact=username) | Q(email__iexact=username)
            )
            print(f"User found: {user}")  # Debug print
            logger.info(f"User found: {user}")

            if user.check_password(password):
                print("Password check successful")  # Debug print
                logger.info("Password check successful")
                return user
            print("Password check failed")  # Debug print
            logger.warning("Password check failed")
            return None

        except UserModel.DoesNotExist:
            print("User not found")  # Debug print
            logger.warning("User not found")
            return None
