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)
            logger.info(f"User found in database: {username}")
            
            # パスワード検証の詳細ログ
            password_valid = check_password(password, user.password)
            logger.debug(f"Password validation for {username}: {password_valid}")
            
            if password_valid:
                logger.info(f"User authenticated successfully: {username}")
                return user
            else:
                logger.warning(f"Password mismatch for user: {username}")
                logger.debug(f"Provided password length: {len(password) if password else 0}")
        except CustomUser.DoesNotExist:
            logger.warning(f"User does not exist: {username}")
        except Exception as e:
            logger.error(f"Authentication error for {username}: {str(e)}")
            import traceback
            logger.error(f"Authentication traceback: {traceback.format_exc()}")
        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
