from dj_rest_auth.registration.serializers import RegisterSerializer
from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()

class CustomRegisterSerializer(RegisterSerializer):
    username = None
    email = serializers.EmailField(required=True)
    def custom_signup(self, request, user):
        user.email = self.data.get('email')
        user.save()


from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
# from django.conf import settings
# from decouple import config
# account_type = config('ACCOUNTTYPE', default=None)
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    """
    Custom serializer to add extra claims to the JWT and only accept email and password.
    """
    email = serializers.EmailField()
    password = serializers.CharField(write_only=True)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.get('context', {}).get('request', None)
        super().__init__(*args, **kwargs)

        self.fields.pop('username', None)

    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        
        # Add custom claims to the token
        token['email'] = user.email
        token['first_name'] = user.first_name
        token['last_name'] = user.last_name
        token['is_superuser'] = user.is_superuser
        return token
    
    # def validate(self, attrs):
    #     """
    #     Validate the email and password and ensure they are correct.
    #     """
    #     email = attrs.get('email')
    #     password = attrs.get('password')

    #     # Validate user using email and password with request context
    #     user = self.authenticate_user( email, password)
    #     if not user:
    #         raise serializers.ValidationError('Invalid email or password.')

    #     # Manually set the username to be the same as email
    #     attrs['username'] = email  # Setting username to email

    #     # Only include necessary user data, NOT the entire CustomUser object
    #     attrs['user'] = {
    #         'email': user.email,
    #         'first_name': user.first_name,
    #         'last_name': user.last_name,
    #         'is_superuser': user.is_superuser,
    #     }

    #     return attrs

    def validate(self, attrs):
        """
        Override validate to authenticate using email instead of username.
        """
        email = attrs.get("email")
        password = attrs.get("password")

        # Retrieve the user model
        User = get_user_model()

        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            raise serializers.ValidationError("Invalid email or password.")

        # Check the password manually
        if not user.check_password(password):
            raise serializers.ValidationError("Invalid email or password.")

        # Use the standard JWT token validation
        data = super().validate({"username": user.get_username(), "password": password})

        return data

    def authenticate_user(self, email, password):
        """
        Custom method to authenticate a user using email and password.
        """
        from django.contrib.auth import authenticate
        
        user = authenticate(self.request, username=email, password=password)
        return user


User = get_user_model()

class BaseEmailCheckSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)

    def validate_email(self, value):
        return value.lower()

    def validate(self, attrs):
        email = attrs.get('email')
        
        user = User.objects.filter(email=email).first()
        if not user:
            raise serializers.ValidationError({
                "email": f"No account found for this email"
            })
            
        attrs['user'] = user
        return attrs

class EmailCheckSerializer(BaseEmailCheckSerializer):
    pass