from django.core.management.base import BaseCommand
from apps.sales.models import Sale, CreditTransaction, CreditLedger
from django.db.models import Q

class Command(BaseCommand):
    help = 'Debug credit transaction creation for sales'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--sale-id',
            type=str,
            help='Specific sale ID to check'
        )
    
    def handle(self, *args, **options):
        sale_id = options.get('sale_id')
        
        if sale_id:
            sales = Sale.objects.filter(id=sale_id)
        else:
            # Get recent sales with credit payments
            sales = Sale.objects.filter(
                payments__payment_mode__name='CREDIT'
            ).distinct().order_by('-created_at')[:10]
        
        for sale in sales:
            self.stdout.write(f"\n{'='*80}")
            self.stdout.write(f"Sale: {sale.sale_number} (ID: {sale.id})")
            self.stdout.write(f"Customer: {sale.customer.name}")
            self.stdout.write(f"Total: {sale.total_amount}")
            self.stdout.write(f"Status: {sale.status}")
            self.stdout.write(f"Created: {sale.created_at}")
            
            # Check credit payments
            credit_payments = sale.payments.filter(payment_mode__name='CREDIT')
            self.stdout.write(f"\nCredit Payments: {credit_payments.count()}")
            for payment in credit_payments:
                self.stdout.write(f"  - Amount: {payment.amount}")
                self.stdout.write(f"    Mode: {payment.payment_mode.name}")
                self.stdout.write(f"    Date: {payment.payment_date}")
            
            # Check CreditTransaction
            credit_txns = CreditTransaction.objects.filter(sale=sale)
            self.stdout.write(f"\nCreditTransactions: {credit_txns.count()}")
            for txn in credit_txns:
                self.stdout.write(
                    f"  - Type: {txn.transaction_type}, "
                    f"Amount: {txn.amount}, "
                    f"Balance After: {txn.balance_after}"
                )
                self.stdout.write(f"    Created: {txn.created_at}")
            
            # Check CreditLedger
            ledger_entries = CreditLedger.objects.filter(sale=sale)
            self.stdout.write(f"\nCreditLedger Entries: {ledger_entries.count()}")
            for entry in ledger_entries:
                self.stdout.write(
                    f"  - Type: {entry.transaction_type}, "
                    f"Debit: {entry.debit_amount}, "
                    f"Credit: {entry.credit_amount}"
                )
                self.stdout.write(f"    Balance After: {entry.balance_after}")
                self.stdout.write(f"    Due Date: {entry.due_date}")
                self.stdout.write(f"    Status: {entry.status}")
            
            # Check customer balance
            self.stdout.write(f"\nCustomer Credit Balance: {sale.customer.current_credit_balance}")
            self.stdout.write(f"Customer Credit Limit: {sale.customer.credit_limit}")
            
            # Analysis
            if credit_payments.exists() and not credit_txns.exists():
                self.stdout.write(self.style.ERROR(
                    "\n⚠️  ISSUE: Credit payments exist but no CreditTransaction found!"
                ))
            elif credit_txns.count() > credit_payments.count():
                self.stdout.write(self.style.WARNING(
                    f"\n⚠️  WARNING: More CreditTransactions ({credit_txns.count()}) "
                    f"than credit payments ({credit_payments.count()})"
                ))
            else:
                self.stdout.write(self.style.SUCCESS(
                    "\n✓ Credit transactions look correct"
                ))
        
        self.stdout.write(f"\n{'='*80}\n")
        self.stdout.write(self.style.SUCCESS('Debug complete!'))