from rest_framework import serializers
from django.contrib.auth import get_user_model
from allauth.account.models import EmailAddress
from .models import ClientesA24

class ClientesA24Serailizer(serializers.ModelSerializer):
    class Meta:
        model =ClientesA24
        fields = ('RFC', 'Nombre','Activo','fecha_baja',)


class SerialiazerA24(serializers.ModelSerializer):
    pass

User = get_user_model()

class SignupSerializer(serializers.Serializer):
    password = serializers.CharField(write_only=True)
    password2 = serializers.CharField(write_only=True)
    class Meta:
        model = User
        fields = ['username', 'password', 'email', 'first_name', 'last_name']
    def validate(self, data):
        print(f'DATA {data}')
        if data['password'] != data['password2']:
            raise serializers.ValidationError("Las contraseñas no coinciden.")
        return data

    def create(self, validated_data):
        print(f'CREATE {validated_data}')
        password2 = validated_data.get('password2')
        if password2:
            validated_data.pop('password2')
        
        # Asegurarse de tener el campo 'username' en validated_data
        username   = self.context['request'].data.get('username')
        email      = self.context['request'].data.get('email')
        first_name = self.context['request'].data.get('first_name')
        last_name  = self.context['request'].data.get('last_name')
        if not username:
            raise serializers.ValidationError("El campo 'username' es requerido.")
        
        # Crear el usuario con los datos validados
        user = User.objects.create_user(username=username, password=validated_data['password'], email=email, first_name=first_name, last_name= last_name)
        # Crea el objeto Email asociado al usuario
        EmailAddress.objects.create(user=user, email=user.email, primary=True, verified=False)
        return user