"""
Сериализаторы для реферальной системы.
"""
from rest_framework import serializers
from .models import (
    ReferralLevel,
    UserReferralProfile,
    BonusAccount,
    ReferralEarning,
    PointsTransaction,
    BonusTransaction,
    PromoCode,
    PromoCodeUsage,
    ReferralSettings
)


class ReferralLevelSerializer(serializers.ModelSerializer):
    """Сериализатор уровня."""
    
    class Meta:
        model = ReferralLevel
        fields = [
            'id',
            'level',
            'name',
            'points_required',
            'bonus_payment_percent',
            'icon'
        ]


class ReferralSettingsSerializer(serializers.ModelSerializer):
    """Сериализатор настроек."""
    
    class Meta:
        model = ReferralSettings
        fields = [
            'level1_commission',
            'level2_commission',
            'points_direct_referral',
            'points_indirect_referral'
        ]


class UserReferralProfileSerializer(serializers.ModelSerializer):
    """Сериализатор реферального профиля."""
    
    current_level = ReferralLevelSerializer(read_only=True)
    referral_link = serializers.SerializerMethodField()
    next_level = serializers.SerializerMethodField()
    
    class Meta:
        model = UserReferralProfile
        fields = [
            'id',
            'referral_code',
            'referral_link',
            'current_level',
            'next_level',
            'total_points',
            'direct_referrals_count',
            'indirect_referrals_count',
            'total_earned',
            'created_at'
        ]
    
    def get_referral_link(self, obj):
        """Получить реферальную ссылку (всегда используем FRONTEND_URL)."""
        from django.conf import settings
        return obj.get_referral_link(settings.FRONTEND_URL)
    
    def get_next_level(self, obj):
        """Получить следующий уровень."""
        if not obj.current_level:
            return None
        
        next_level = ReferralLevel.objects.filter(
            level__gt=obj.current_level.level
        ).order_by('level').first()
        
        if next_level:
            return {
                'level': next_level.level,
                'name': next_level.name,
                'points_required': next_level.points_required,
                'points_to_next': next_level.points_required - obj.total_points
            }
        return None


class BonusAccountSerializer(serializers.ModelSerializer):
    """Сериализатор бонусного счета."""
    
    class Meta:
        model = BonusAccount
        fields = [
            'id',
            'balance',
            'total_earned',
            'total_spent',
            'created_at',
            'updated_at'
        ]


class ReferralEarningSerializer(serializers.ModelSerializer):
    """Сериализатор заработка с реферала."""
    
    referral_email = serializers.EmailField(source='referral.email', read_only=True)
    
    class Meta:
        model = ReferralEarning
        fields = [
            'id',
            'referral_email',
            'level',
            'payment_amount',
            'commission_percent',
            'earned_amount',
            'created_at'
        ]


class PointsTransactionSerializer(serializers.ModelSerializer):
    """Сериализатор транзакции очков."""
    
    class Meta:
        model = PointsTransaction
        fields = [
            'id',
            'points',
            'reason',
            'balance_after',
            'created_at'
        ]


class BonusTransactionSerializer(serializers.ModelSerializer):
    """Сериализатор транзакции бонусов."""
    
    class Meta:
        model = BonusTransaction
        fields = [
            'id',
            'amount',
            'transaction_type',
            'reason',
            'balance_after',
            'created_at'
        ]


class PromoCodeSerializer(serializers.ModelSerializer):
    """Сериализатор промокода."""
    
    is_valid_now = serializers.SerializerMethodField()
    usage_count = serializers.IntegerField(source='current_uses', read_only=True)
    
    class Meta:
        model = PromoCode
        fields = [
            'id',
            'code',
            'name',
            'description',
            'discount_type',
            'discount_value',
            'max_uses',
            'usage_count',
            'valid_until',
            'is_active',
            'is_valid_now'
        ]
    
    def get_is_valid_now(self, obj):
        """Проверить валидность."""
        is_valid, _ = obj.is_valid()
        return is_valid


class PromoCodeValidationSerializer(serializers.Serializer):
    """Сериализатор для валидации промокода."""
    
    code = serializers.CharField(max_length=50)
    plan_id = serializers.IntegerField()


class PromoCodeUsageSerializer(serializers.ModelSerializer):
    """Сериализатор использования промокода."""
    
    promo_code_code = serializers.CharField(source='promo_code.code', read_only=True)
    
    class Meta:
        model = PromoCodeUsage
        fields = [
            'id',
            'promo_code_code',
            'original_amount',
            'discount_amount',
            'final_amount',
            'created_at'
        ]


class SetReferrerSerializer(serializers.Serializer):
    """Сериализатор для установки реферера."""
    
    referral_code = serializers.CharField(max_length=20)
    
    def validate_referral_code(self, value):
        """Валидация реферального кода."""
        try:
            profile = UserReferralProfile.objects.get(referral_code=value)
            return value
        except UserReferralProfile.DoesNotExist:
            raise serializers.ValidationError('Неверный реферальный код')

