"""
User models for the crypto trading platform.
"""
import uuid
from django.contrib.auth.models import AbstractUser
from django.db import models


class User(AbstractUser):
    """
    Custom User model extending Django's AbstractUser.
    Includes additional fields for the crypto trading platform.
    """
    
    # Referral system fields
    referral_code = models.CharField(max_length=20, unique=True, blank=True)
    referred_by = models.ForeignKey(
        'self', 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        related_name='referred_users'
    )
    
    # Wallet fields
    wallet_balance = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    total_earnings = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    referral_earnings = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    
    # Profile fields
    phone = models.CharField(max_length=20, blank=True)
    address = models.TextField(blank=True)
    country = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100, blank=True)
    postal_code = models.CharField(max_length=20, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    profile_image = models.ImageField(upload_to='profile_images/', null=True, blank=True)
    id_card_image = models.ImageField(upload_to='verification/id_cards/', null=True, blank=True)
    selfie_image = models.ImageField(upload_to='verification/selfies/', null=True, blank=True)
    bio = models.TextField(blank=True)
    
    # Account status
    is_active_signal = models.BooleanField(default=True)
    is_verified = models.BooleanField(default=False)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.username} ({self.email})"
    
    def save(self, *args, **kwargs):
        if not self.referral_code:
            self.referral_code = self.generate_referral_code()
        super().save(*args, **kwargs)
    
    def generate_referral_code(self):
        """Generate a unique referral code for the user."""
        return f"REF{uuid.uuid4().hex[:8].upper()}"
    
    def get_referral_link(self):
        """Get the referral link for this user."""
        return f"/signup/?ref={self.referral_code}"
    
    def get_total_referrals(self):
        """Get total number of direct referrals."""
        return self.referred_users.count()
    
    def get_full_name(self):
        """Get user's full name."""
        if self.first_name and self.last_name:
            return f"{self.first_name} {self.last_name}"
        return self.username

    @property
    def has_submitted_verification(self):
        """Return True when both verification documents are available."""
        return bool(self.id_card_image and self.selfie_image)

    @property
    def verification_status(self):
        """Return the current verification state for the user."""
        if self.is_verified:
            return 'VERIFIED'
        if self.has_submitted_verification:
            return 'PENDING'
        return 'UNVERIFIED'

    @property
    def verification_status_label(self):
        """Human-readable label for the current verification state."""
        labels = {
            'VERIFIED': 'Verified',
            'PENDING': 'Pending Review',
            'UNVERIFIED': 'Not Submitted',
        }
        return labels[self.verification_status]
