from rest_framework import serializers
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from dj_rest_auth.registration.serializers import RegisterSerializer
from dj_rest_auth.serializers import UserDetailsSerializer
from .models import ParadiseUser


class ParadiseUserSerializer(serializers.ModelSerializer):
    """
    用于用户数据完整操作的序列化器
    管理员使用
    """
    class Meta:
        model = ParadiseUser
        fields = '__all__'
        extra_kwargs = {
            'password': {'write_only': True}  # 确保密码字段永远不会被序列化返回
        }


class UserInfoSerializer(serializers.ModelSerializer):
    """
    用于展示用户信息的序列化器
    用户自己查看
    """
    class Meta:
        model = ParadiseUser
        fields = ['id', 'username', 'email', 'phone_number', 'date_joined', 'last_login', 
                 'favorability', 'gender', 'resident_city', 'birthday', 'zodiac_sign', 
                 'mbti', 'interests', 'social_identity']
        read_only_fields = ['id', 'date_joined', 'last_login']


class ProfileUpdateSerializer(serializers.ModelSerializer):
    """
    用于用户更新个人资料的序列化器
    """
    class Meta:
        model = ParadiseUser
        fields = ['gender', 'resident_city', 'birthday', 'zodiac_sign', 
                 'mbti', 'interests', 'social_identity']


class CustomUserDetailsSerializer(UserDetailsSerializer):
    """
    自定义 dj_rest_auth 用户详情序列化器
    确保不返回敏感字段
    """
    class Meta(UserDetailsSerializer.Meta):
        model = ParadiseUser
        exclude = ['password', 'user_permissions', 'groups']
        read_only_fields = ['id', 'date_joined', 'last_login']


class CustomRegisterSerializer(RegisterSerializer):
    email = serializers.EmailField(required=False)
    phone_number = serializers.CharField(required=False, allow_blank=True, max_length=15)

    def get_cleaned_data(self):
        data = super().get_cleaned_data()
        data['phone_number'] = self.validated_data.get('phone_number', '')
        return data

    def save(self, request):
        user = super().save(request)
        user.phone_number = self.cleaned_data.get('phone_number')
        user.save()
        return user


