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

User = get_user_model()


class TransactionType(models.TextChoices):
    DEPOSIT = 'DEPOSIT', 'Deposit'
    WITHDRAWAL = 'WITHDRAWAL', 'Withdrawal'
    REFERRAL_BONUS = 'REFERRAL_BONUS', 'Referral Bonus'
    SIGNAL_PURCHASE = 'SIGNAL_PURCHASE', 'Signal Purchase'
    SIGNAL_PROFIT = 'SIGNAL_PROFIT', 'Signal Profit'
    OTHER = 'OTHER', 'Other'


class TransactionStatus(models.TextChoices):
    PENDING = 'PENDING', 'Pending'
    COMPLETED = 'COMPLETED', 'Completed'
    FAILED = 'FAILED', 'Failed'
    CANCELLED = 'CANCELLED', 'Cancelled'


class WithdrawalMethod(models.TextChoices):
    BITCOIN = 'BITCOIN', 'Bitcoin'
    ETHEREUM = 'ETHEREUM', 'Ethereum'
    USDT_TRC20 = 'USDT_TRC20', 'USDT (TRC20)'
    USDT_ERC20 = 'USDT_ERC20', 'USDT (ERC20)'
    BANK_TRANSFER = 'BANK_TRANSFER', 'Bank Transfer'
    OTHER = 'OTHER', 'Other'


class WithdrawalStatus(models.TextChoices):
    PENDING = 'PENDING', 'Pending'
    APPROVED = 'APPROVED', 'Approved'
    REJECTED = 'REJECTED', 'Rejected'


class Wallet(models.Model):
    """
    Model to store user's wallet information.
    Each user has one wallet.
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='wallet')
    balance = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    total_deposits = models.DecimalField(max_digits=15, decimal_places=2, default=0.00)
    total_withdrawals = 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)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        verbose_name = 'Wallet'
        verbose_name_plural = 'Wallets'
    
    def __str__(self):
        return f"Wallet - {self.user.username}"
    
    def credit_balance(self, amount, transaction_type, description=''):
        """Credit balance to wallet."""
        self.balance += amount
        self.total_earnings += amount
        if transaction_type == TransactionType.REFERRAL_BONUS:
            self.referral_earnings += amount
        self.save()
    
    def debit_balance(self, amount, transaction_type, description=''):
        """Debit balance from wallet."""
        if self.balance >= amount:
            self.balance -= amount
            if transaction_type == TransactionType.WITHDRAWAL:
                self.total_withdrawals += amount
            self.save()
            return True
        return False


class Transaction(models.Model):
    """
    Model to track all wallet transactions.
    """
    wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE, related_name='transactions')
    transaction_type = models.CharField(max_length=20, choices=TransactionType.choices)
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    status = models.CharField(max_length=20, choices=TransactionStatus.choices, default=TransactionStatus.PENDING)
    description = models.TextField(blank=True)
    reference_id = models.CharField(max_length=100, blank=True)
    
    # Timestamps
    created_at = models.DateTimeField(auto_now_add=True)
    completed_at = models.DateTimeField(null=True, blank=True)
    
    class Meta:
        verbose_name = 'Transaction'
        verbose_name_plural = 'Transactions'
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.wallet.user.username} - {self.transaction_type} - {self.amount}"


class WithdrawalRequest(models.Model):
    """
    Model to store user withdrawal requests for admin review.
    """
    wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE, related_name='withdrawal_requests')
    amount = models.DecimalField(max_digits=15, decimal_places=2)
    method = models.CharField(max_length=50, choices=WithdrawalMethod.choices)
    destination_details = models.CharField(max_length=255)
    notes = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=WithdrawalStatus.choices, default=WithdrawalStatus.PENDING)
    transaction = models.OneToOneField(
        Transaction,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='withdrawal_request'
    )
    reviewed_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='reviewed_withdrawals'
    )
    reviewed_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Withdrawal Request'
        verbose_name_plural = 'Withdrawal Requests'
        ordering = ['-created_at']

    def __str__(self):
        return f"Withdrawal #{self.id} - {self.wallet.user.username} - {self.amount}"
