"""
Management command to set up production M-Pesa configuration
"""
from django.core.management.base import BaseCommand
from django.conf import settings
from payments.models import MpesaConfiguration
from users.models import Branch


class Command(BaseCommand):
    help = 'Set up production M-Pesa configuration with the provided credentials'

    def add_arguments(self, parser):
        parser.add_argument(
            '--update-branches',
            action='store_true',
            help='Update all branches with the default M-Pesa configuration',
        )

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('Setting up production M-Pesa configuration...'))
        
        # Create or update the main M-Pesa configuration
        config, created = MpesaConfiguration.objects.get_or_create(
            business_short_code='4159523',
            defaults={
                'environment': 'production',
                'consumer_key': '9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr',
                'consumer_secret': 'C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR',
                'passkey': '',  # You'll need to add the passkey when available
                'validation_url': f"https://branchbusinessadvance.co.ke/payments/callback/validation/",
                'confirmation_url': f"https://branchbusinessadvance.co.ke/payments/callback/confirmation/",
                'response_type': 'Completed',
                'is_active': True,
            }
        )
        
        if created:
            self.stdout.write(self.style.SUCCESS(f'Created M-Pesa configuration for shortcode {config.business_short_code}'))
        else:
            self.stdout.write(self.style.WARNING(f'M-Pesa configuration for shortcode {config.business_short_code} already exists'))
        
        # Update branches if requested
        if options['update_branches']:
            self.stdout.write(self.style.SUCCESS('Updating branch M-Pesa configurations...'))
            
            branches = Branch.objects.all()
            updated_count = 0
            
            for branch in branches:
                if not branch.mpesa_shortcode:
                    branch.mpesa_shortcode = '4159523'
                    branch.mpesa_consumer_key = '9mD1A3H1qw5grqdqkZ4X1G9zbNxioydHXL5An4nkUGRlNRKr'
                    branch.mpesa_consumer_secret = 'C2dqBSaGFUIporfYYuyhQgnfPEqLvCS3GvfAJ91ENkXI2bhqptlVXAqMelsEpLQR'
                    branch.save()
                    updated_count += 1
                    self.stdout.write(f'  Updated branch: {branch.name}')
            
            self.stdout.write(self.style.SUCCESS(f'Updated {updated_count} branches with M-Pesa configuration'))
        
        # Register C2B URLs
        try:
            from payments.branch_mpesa_service import BranchMpesaService
            
            service = BranchMpesaService()
            result = service.register_c2b_urls()
            
            self.stdout.write(self.style.SUCCESS('C2B URLs registered successfully with M-Pesa'))
            self.stdout.write(f'   Response: {result}')
            
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'Failed to register C2B URLs: {str(e)}'))
            self.stdout.write(self.style.WARNING('You may need to register the URLs manually in the M-Pesa portal'))
        
        self.stdout.write(self.style.SUCCESS('\nM-Pesa setup completed!'))
        self.stdout.write(self.style.SUCCESS('\nNext steps:'))
        self.stdout.write('1. Add the passkey to the M-Pesa configuration when available')
        self.stdout.write('2. Test the integration with a small payment')
        self.stdout.write('3. Monitor the admin dashboard for incoming payments')
        self.stdout.write(f'\nAdmin dashboard: https://branchbusinessadvance.co.ke/payments/dashboard/')
