from django.contrib.auth.backends import ModelBackend, BaseBackend
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import get_user_model
import uuid
from django.conf import settings
import logging
logger = logging.getLogger(__name__)

class SessionEnhancingAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        """
        Override the authenticate method to add custom attributes to the session.
        Authenticate using email rather than username.
        """
        # Use email to look up the user
        if username is not None:
            try:
                user = get_user_model().objects.get(email=username)
            except get_user_model().DoesNotExist:
                return None

            if user.check_password(password):
                if user and user.is_authenticated:
                    extra_fields = ['is_active', 'is_superuser', 'is_staff', 'email']
                    existing_fields = [field for field in extra_fields if hasattr(user, field)]

                    # Set custom session attributes
                    [request.session.__setitem__(f"user_{field}", getattr(user, field)) for field in existing_fields]

                    request.session["account_type"] = settings.AUTH_IDENTIFIER

                return user
        return None
