from django.conf import settings
#from django.contrib.auth import get_user_model
from .models import CustomUser
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import check_password
import logging

logger = logging.getLogger(__name__)


class EmailOrUsernameModelBackend(ModelBackend):
    """
    This is a ModelBacked that allows authentication
    with either a username or an email address.
    
    """
    """
    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = CustomUser.objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
        try:
            return CustomUser.objects.get(pk=username)
        except get_user_model().DoesNotExist:
            return None
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}
        try:
            user = CustomUser.objects.get(**kwargs)
            if check_password(password, user.password):
                logger.info(f"User authenticated successfully: {username}")
                return user
            else:
                logger.warning(f"Password mismatch for user: {username}")
        except CustomUser.DoesNotExist:
            logger.warning(f"User does not exist: {username}")
        except Exception as e:
            logger.error(f"Authentication error for {username}: {str(e)}")
        return None

    def get_user(self, user_id):
        try:
            user = CustomUser.objects.get(pk=user_id)
            logger.info(f"User retrieved: {user.username or user.email}")
            return user
        except CustomUser.DoesNotExist:
            logger.warning(f"User with id {user_id} does not exist")
            return None
        except Exception as e:
            logger.error(f"Error retrieving user with id {user_id}: {str(e)}")
            return None
