"""
Management command to fix amount_xof for existing donations.

This command populates the amount_xof field for donations that have an amount
but amount_xof is 0 or null. This is needed for donations created before the
currency conversion system was implemented.

Usage:
    python manage.py fix_donation_amounts
"""

from django.core.management.base import BaseCommand
from django.db.models import Sum
from appsponsor.models import Donation
from appsponsor.currency_service import CurrencyService


class Command(BaseCommand):
    help = 'Fix amount_xof for existing donations that have amount > 0 but amount_xof = 0'

    def handle(self, *args, **options):
        self.stdout.write(self.style.WARNING('Starting donation amount fix...'))
        
        # Find donations with amount > 0 but amount_xof = 0
        donations_to_fix = Donation.objects.filter(
            amount__gt=0,
            amount_xof=0
        )
        
        total_count = donations_to_fix.count()
        self.stdout.write(f'Found {total_count} donations to fix')
        
        if total_count == 0:
            self.stdout.write(self.style.SUCCESS('No donations need fixing!'))
            return
        
        # Fix each donation
        fixed_count = 0
        for donation in donations_to_fix:
            try:
                # Convert amount to XOF using CurrencyService
                amount_xof = CurrencyService.to_xof(
                    donation.amount,
                    donation.currency
                )
                
                # Update the donation
                donation.amount_xof = amount_xof
                donation.save(update_fields=['amount_xof'])
                
                fixed_count += 1
                self.stdout.write(
                    f'✓ Fixed donation #{donation.id}: '
                    f'{donation.amount} {donation.currency} → {amount_xof} XOF'
                )
                
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(
                        f'✗ Failed to fix donation #{donation.id}: {str(e)}'
                    )
                )
        
        # Show summary
        self.stdout.write('\n' + '='*60)
        self.stdout.write(self.style.SUCCESS(
            f'Successfully fixed {fixed_count} out of {total_count} donations'
        ))
        
        # Calculate and display total approved amount
        total_approved = Donation.objects.filter(
            status='approved'
        ).aggregate(total=Sum('amount_xof'))['total'] or 0
        
        self.stdout.write(self.style.SUCCESS(
            f'Total approved amount: {total_approved:,.0f} FCFA'
        ))
        self.stdout.write('='*60)
