"""
Referral models for the crypto trading platform.
"""
from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class ReferralEarningType(models.TextChoices):
    REFERRER_BONUS = 'REFERRER_BONUS', 'Referrer Bonus'
    REFERRED_USER_BONUS = 'REFERRED_USER_BONUS', 'Referred User Bonus'
    TEAM_BONUS = 'TEAM_BONUS', 'Team Bonus'


class ReferralCommission(models.Model):
    """
    Model to store referral team level settings.
    """
    level = models.PositiveIntegerField(default=1)
    percentage = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
    required_members = models.PositiveIntegerField(default=5)
    bonus_amount = models.DecimalField(max_digits=15, decimal_places=2, default=250.00)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Referral Level'
        verbose_name_plural = 'Referral Levels'
        ordering = ['level']
    
    def __str__(self):
        return f"Level {self.level} - {self.required_members} members - ${self.bonus_amount}"


class ReferralProgramSettings(models.Model):
    """
    Global referral program settings editable from admin.
    """
    referrer_bonus_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=10.00)
    referred_user_bonus_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=5.00)
    minimum_deposit_amount = models.DecimalField(max_digits=15, decimal_places=2, default=300.00)
    maximum_deposit_amount = models.DecimalField(max_digits=15, decimal_places=2, default=5000.00)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Referral Program Setting'
        verbose_name_plural = 'Referral Program Settings'

    def __str__(self):
        return 'Referral Program Settings'


class ReferralEarning(models.Model):
    """
    Model to track referral earnings for users.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_referral_earnings')
    referred_user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='referred_user_earnings',
        null=True,
        blank=True
    )
    commission = models.ForeignKey(ReferralCommission, on_delete=models.SET_NULL, null=True)
    deposit = models.ForeignKey(
        'deposits.Deposit',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='referral_earnings'
    )
    earning_type = models.CharField(
        max_length=30,
        choices=ReferralEarningType.choices,
        default=ReferralEarningType.REFERRER_BONUS
    )
    percentage_applied = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    level_achieved = models.PositiveIntegerField(null=True, blank=True)
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    deposit_amount = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    is_credited = models.BooleanField(default=False)
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = 'Referral Earning'
        verbose_name_plural = 'Referral Earnings'
        ordering = ['-created_at']
    
    def __str__(self):
        source = self.referred_user.username if self.referred_user else f"Level {self.level_achieved or '-'}"
        return f"{self.user.username} earned {self.amount} from {source}"
