from rest_framework import serializers
from .models import Achievement, UserAchievement

class AchievementSerializer(serializers.ModelSerializer):
    """
    成就序列化器
    """
    class Meta:
        model = Achievement
        fields = (
            'id', 'name', 'description', 'icon', 'rarity', 
            'achievement_type', 'is_hidden', 'points', 
            'created_at', 'updated_at'
        )
        read_only_fields = ('created_at', 'updated_at')
        
    def to_representation(self, instance):
        """自定义输出格式"""
        ret = super().to_representation(instance)
        # 将稀有度和成就类型的显示名称添加到响应中
        ret['rarity_display'] = instance.get_rarity_display()
        ret['type_display'] = instance.get_achievement_type_display()
        return ret


class UserAchievementSerializer(serializers.ModelSerializer):
    """
    用户成就关联序列化器
    """
    achievement = AchievementSerializer(read_only=True)
    
    class Meta:
        model = UserAchievement
        fields = (
            'id', 'user', 'achievement', 'acquired_at',
            'acquisition_data', 'notification_shown'
        )
        read_only_fields = ('acquired_at',)
        

class UserAchievementCreateSerializer(serializers.ModelSerializer):
    """
    用户成就关联创建序列化器（用于管理端）
    """
    class Meta:
        model = UserAchievement
        fields = ('user', 'achievement', 'acquisition_data', 'notification_shown')


class UserAchievementListSerializer(serializers.ModelSerializer):
    """
    用户获取的成就列表序列化器
    """
    achievement = AchievementSerializer(read_only=True)
    
    class Meta:
        model = UserAchievement
        fields = ('id', 'achievement', 'acquired_at', 'acquisition_data')
        read_only_fields = ('id', 'achievement', 'acquired_at', 'acquisition_data') 