from django.db import models
from django.contrib.auth.models import User

STATUS = (
    ('pending', 'Pending'),
    ('approved', 'Approved'),
    ('rejected', 'Rejected'),
)

def log_action(user, action, details=''):
    """Helper function to log actions"""
    try:
        from audits.models import Log
        Log.objects.create(user=user, action=action, details=details)
    except Exception as e:
        import logging
        logging.getLogger(__name__).error(f"Failed to log action: {e}")

class Sponsorship(models.Model):
    SPONSORSHIP_CHOICES = [
        ('diamond', 'Diamond'),
        ('gold', 'Gold'),
        ('silver', 'Silver'),
    ]

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    sponsorship_level = models.CharField(max_length=20, choices=SPONSORSHIP_CHOICES, blank=True, null=True)
    status = models.CharField(max_length=20, choices=STATUS, default='pending')
    
    # Fields for tracking who created and updated the record
    created_by = models.CharField(max_length=255, default='', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True, editable=False)
    updated_by = models.CharField(max_length=255, default='', null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, editable=False)

    def __str__(self):
        return f"{self.user.username} - {self.get_sponsorship_level_display() if self.sponsorship_level else 'No Sponsorship'}"
    
    def save(self, *args, **kwargs):
        is_new = self.pk is None
        super().save(*args, **kwargs)
        action = f"Created sponsorship: {self.sponsorship_level or 'None'}" if is_new else f"Updated sponsorship: {self.sponsorship_level or 'None'}"
        log_action(self.user, action, f"Level: {self.sponsorship_level}, Status: {self.status}, Updated by: {self.updated_by}")


class Donation(models.Model):
    PROVIDER_CHOICES = [
        ('paytech', 'PayTech'),
        ('paydunya', 'Paydunya'),
    ]
    
    CURRENCY_CHOICES = [
        ('XOF', 'CFA Franc (FCFA)'),
        ('EUR', 'Euro (€)'),
        ('USD', 'US Dollar ($)'),
        ('GBP', 'British Pound (£)'),
        ('CAD', 'Canadian Dollar (C$)'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    
    # Currency and amount fields
    currency = models.CharField(
        max_length=3,
        choices=CURRENCY_CHOICES,
        default='XOF',
        help_text='Currency selected by donor'
    )
    amount = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00,
        blank=True,
        null=True,
        help_text='Amount in selected currency'
    )
    amount_xof = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0.00,
        blank=True,
        null=True,
        help_text='Amount converted to XOF for reporting'
    )
    exchange_rate = models.DecimalField(
        max_digits=10,
        decimal_places=4,
        default=1.0000,
        help_text='Exchange rate used for conversion (1 CURRENCY = X XOF)'
    )
    
    status = models.CharField(max_length=20, choices=STATUS, default='pending')

    # Payment provider tracking
    payment_provider = models.CharField(max_length=20, choices=PROVIDER_CHOICES, default='paytech')
    invoice_token = models.CharField(max_length=100, blank=True, null=True, help_text='Payment gateway invoice/transaction token')
    receipt_url = models.URLField(blank=True, null=True, help_text='PDF receipt URL from Paydunya')

    # # To track the purpose of the donation
    # purpose = models.CharField(max_length=255, blank=True, null=True)

    # Fields for tracking who created and updated the record
    created_by = models.CharField(max_length=255, default='', null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True, editable=False)
    updated_by = models.CharField(max_length=255, default='', null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True, null=True, editable=False)
    
    def __str__(self):
        if self.created_at:
            return f"Donation by {self.created_by}: {self.amount} {self.currency} ({self.amount_xof} XOF) on {self.created_at.strftime('%Y-%m-%d')}"
        return f"Donation by {self.created_by}: {self.amount} {self.currency}"
    
    def save(self, *args, **kwargs):
        # Auto-calculate amount_xof if not already set
        if self.amount and self.currency and not self.amount_xof:
            from .currency_service import CurrencyService
            self.amount_xof = CurrencyService.to_xof(self.amount, self.currency)
            self.exchange_rate = CurrencyService.get_exchange_rate(self.currency)
        
        is_new = self.pk is None
        super().save(*args, **kwargs)
        
        # Log action with currency info
        action = f"Created donation: {self.amount} {self.currency}" if is_new else "Updated donation"
        details = f"Amount: {self.amount} {self.currency} = {self.amount_xof} XOF, Status: {self.status}, Rate: {self.exchange_rate}, Updated by: {self.updated_by}"
        log_action(self.user, action, details)
