"""
Management command to show recent M-Pesa transactions
"""
from django.core.management.base import BaseCommand
from loans.models import MpesaTransaction
from django.contrib.auth import get_user_model

User = get_user_model()


class Command(BaseCommand):
    help = 'Show recent M-Pesa transactions'

    def add_arguments(self, parser):
        parser.add_argument(
            '--limit',
            type=int,
            default=10,
            help='Number of transactions to show (default: 10)',
        )

    def handle(self, *args, **options):
        limit = options.get('limit', 10)
        
        self.stdout.write(self.style.SUCCESS(f'Recent M-Pesa Transactions (Last {limit}):'))
        self.stdout.write('=' * 80)
        
        transactions = MpesaTransaction.objects.order_by('-created_at')[:limit]
        
        if not transactions:
            self.stdout.write(self.style.WARNING('No M-Pesa transactions found'))
            return
        
        for i, t in enumerate(transactions, 1):
            self.stdout.write(f'\n{i}. Transaction ID: {t.id}')
            self.stdout.write(f'   Type: {t.transaction_type}')
            self.stdout.write(f'   Amount: KES {t.amount:,.2f}')
            self.stdout.write(f'   Phone: {t.phone_number}')
            self.stdout.write(f'   Status: {t.status}')
            self.stdout.write(f'   Payment Source: {t.payment_source} {"(Automatic)" if t.is_automatic else "(Manual)"}')
            self.stdout.write(f'   M-Pesa Trans ID: {t.trans_id or t.mpesa_transaction_id or "N/A"}')
            self.stdout.write(f'   Borrower: {t.borrower.get_full_name() if t.borrower else "Not matched"}')
            self.stdout.write(f'   Loan: {t.loan.loan_number if t.loan else "Not matched"}')
            try:
                repayment_info = t.repayment.receipt_number if t.repayment else "Not created"
            except:
                repayment_info = "Not created"
            self.stdout.write(f'   Repayment: {repayment_info}')
            self.stdout.write(f'   Created: {t.created_at.strftime("%Y-%m-%d %H:%M:%S")}')
            
            if t.processing_notes:
                self.stdout.write(f'   Notes: {t.processing_notes}')
        
        self.stdout.write('\n' + '=' * 80)
        self.stdout.write(self.style.SUCCESS('To view these transactions in Django Admin:'))
        self.stdout.write('1. Go to: /admin/loans/mpesatransaction/')
        self.stdout.write('2. Or go to: /admin/ and click on "Mpesa transactions" under "LOANS"')
        self.stdout.write('3. You can filter by status, payment source, and search by phone number')
        self.stdout.write('\nTo view repayments:')
        self.stdout.write('1. Go to: /admin/loans/repayment/')
        self.stdout.write('2. Look for payments with "Payment source: Automatic M-Pesa"')
