from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from at_django_boilerplate.utils.hash_utils import hexdigest
import logging

logger = logging.getLogger(__name__)

class CustomAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        print('Username:',username)
        if username is None:
            username = kwargs.get('email')  # fallback if email is passed explicitly
        print('Username:',username)

        if not username or not password:
            return None

        username = username.lower()
        email_hash = hexdigest(username)
        user_found=False

        UserModel = get_user_model()


        try:
            user = UserModel.objects.get_by_email(email=username)
            if user:
                user_found=True
            
        except UserModel.DoesNotExist:
            logger.info(f'User with email {username} not found.')


        try:
            if not user_found:
                user = UserModel.objects.get_by_contact_number(contact_number=username)
                if user:
                    user_found=True
        except UserModel.DoesNotExist:
            logger.info(f'User with contact_number {username} not found.')
            return None
            
        if user_found:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

        logger.info(f'Authentication failed for user with email hash {email_hash}.')
        return None

    def user_can_authenticate(self, user):
        return user.is_active
