"""
Django management command to check if repayment was created for M-Pesa transaction
"""
from django.core.management.base import BaseCommand
from loans.models import MpesaTransaction, Repayment


class Command(BaseCommand):
    help = 'Check if repayment was created for M-Pesa transaction'

    def add_arguments(self, parser):
        parser.add_argument(
            'transaction_id',
            type=str,
            help='Transaction ID or M-Pesa TransID',
        )

    def handle(self, *args, **options):
        transaction_id = options['transaction_id']
        
        self.stdout.write(self.style.SUCCESS('='*70))
        self.stdout.write(self.style.SUCCESS('Check M-Pesa Transaction Repayment'))
        self.stdout.write(self.style.SUCCESS('='*70))
        
        # Find transaction
        try:
            transaction = MpesaTransaction.objects.get(id=transaction_id)
        except MpesaTransaction.DoesNotExist:
            try:
                transaction = MpesaTransaction.objects.get(trans_id=transaction_id)
            except MpesaTransaction.DoesNotExist:
                self.stdout.write(self.style.ERROR(f'Transaction not found: {transaction_id}'))
                return
        
        self.stdout.write(f'\nTransaction: {transaction.trans_id}')
        self.stdout.write(f'Amount: KES {transaction.amount}')
        self.stdout.write(f'Status: {transaction.status}')
        self.stdout.write(f'Borrower: {transaction.borrower.get_full_name() if transaction.borrower else "Not matched"}')
        self.stdout.write(f'Loan: {transaction.loan.loan_number if transaction.loan else "Not matched"}')
        
        # Check for repayment using the transaction's repayment_id field
        self.stdout.write('\n' + '='*70)
        self.stdout.write('Checking Repayment...')
        self.stdout.write('='*70)
        
        # Method 1: Check repayment field on transaction
        try:
            if hasattr(transaction, 'repayment_id') and transaction.repayment_id:
                self.stdout.write(f'\nTransaction has repayment_id: {transaction.repayment_id}')
                
                # Try to get the repayment
                try:
                    repayment = Repayment.objects.get(id=transaction.repayment_id)
                    self.stdout.write(self.style.SUCCESS(f'✓ Repayment found: {repayment.receipt_number}'))
                    self.stdout.write(f'  Amount: KES {repayment.amount}')
                    self.stdout.write(f'  Loan: {repayment.loan.loan_number}')
                    self.stdout.write(f'  Payment Method: {repayment.payment_method}')
                    self.stdout.write(f'  Payment Source: {repayment.payment_source}')
                    self.stdout.write(f'  Created: {repayment.created_at}')
                except Repayment.DoesNotExist:
                    self.stdout.write(self.style.ERROR(f'✗ Repayment ID exists but repayment not found in database'))
            else:
                self.stdout.write(self.style.WARNING('✗ Transaction has no repayment_id'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Error checking repayment field: {e}'))
        
        # Method 2: Search for repayment by transaction reference
        self.stdout.write('\n' + '-'*70)
        self.stdout.write('Searching for repayment by transaction...')
        self.stdout.write('-'*70)
        
        repayments = Repayment.objects.filter(
            loan=transaction.loan,
            amount=transaction.amount,
            payment_method='mpesa'
        ).order_by('-created_at')
        
        if repayments.exists():
            self.stdout.write(self.style.SUCCESS(f'\n✓ Found {repayments.count()} matching repayment(s):'))
            for rep in repayments[:5]:
                self.stdout.write(f'\n  Receipt: {rep.receipt_number}')
                self.stdout.write(f'  Amount: KES {rep.amount}')
                self.stdout.write(f'  Created: {rep.created_at}')
                self.stdout.write(f'  Payment Method: {rep.payment_method}')
                self.stdout.write(f'  Payment Source: {rep.payment_source}')
                
                # Check if this repayment is linked back to transaction
                linked_transactions = MpesaTransaction.objects.filter(repayment_id=rep.id)
                if linked_transactions.exists():
                    self.stdout.write(f'  Linked to transaction: {linked_transactions.first().trans_id}')
                else:
                    self.stdout.write('  Not linked to any transaction')
        else:
            self.stdout.write(self.style.WARNING('\n✗ No matching repayments found'))
        
        # Method 3: Check all recent repayments for this loan
        if transaction.loan:
            self.stdout.write('\n' + '-'*70)
            self.stdout.write(f'All recent repayments for {transaction.loan.loan_number}:')
            self.stdout.write('-'*70)
            
            all_repayments = Repayment.objects.filter(
                loan=transaction.loan
            ).order_by('-created_at')[:10]
            
            if all_repayments.exists():
                for rep in all_repayments:
                    self.stdout.write(f'\n  {rep.receipt_number}')
                    self.stdout.write(f'    Amount: KES {rep.amount}')
                    self.stdout.write(f'    Method: {rep.payment_method}')
                    self.stdout.write(f'    Source: {rep.payment_source}')
                    self.stdout.write(f'    Date: {rep.created_at}')
            else:
                self.stdout.write('\nNo repayments found for this loan')
        
        # Summary
        self.stdout.write('\n' + '='*70)
        self.stdout.write('SUMMARY')
        self.stdout.write('='*70)
        
        if hasattr(transaction, 'repayment_id') and transaction.repayment_id:
            try:
                repayment = Repayment.objects.get(id=transaction.repayment_id)
                self.stdout.write(self.style.SUCCESS('\n✓ Repayment exists and is linked'))
                self.stdout.write(f'\nTo view it:')
                self.stdout.write(f'  • /loans/repayments/ - Look for {repayment.receipt_number}')
                self.stdout.write(f'  • /loans/ - Check loan {transaction.loan.loan_number}')
                self.stdout.write(f'  • /payments/transactions/ - Transaction details')
                
                # Check if it should be visible
                self.stdout.write(f'\nRepayment details:')
                self.stdout.write(f'  ID: {repayment.id}')
                self.stdout.write(f'  Receipt: {repayment.receipt_number}')
                self.stdout.write(f'  Loan: {repayment.loan.loan_number}')
                self.stdout.write(f'  Borrower: {repayment.loan.borrower.get_full_name()}')
                self.stdout.write(f'  Amount: KES {repayment.amount}')
                self.stdout.write(f'  Method: {repayment.payment_method}')
                self.stdout.write(f'  Source: {repayment.payment_source}')
                
            except Repayment.DoesNotExist:
                self.stdout.write(self.style.ERROR('\n✗ Repayment ID exists but repayment not in database'))
                self.stdout.write('\nThis is a data integrity issue. The repayment may have been deleted.')
        else:
            self.stdout.write(self.style.WARNING('\n✗ No repayment linked to this transaction'))
            self.stdout.write('\nPossible reasons:')
            self.stdout.write('  • Repayment creation failed')
            self.stdout.write('  • Transaction was not fully processed')
            self.stdout.write('  • Database error occurred')
        
        self.stdout.write('\n')
