"""
Django management command to fix production database issues
Run with: python manage.py fix_production_db
"""
from django.core.management.base import BaseCommand
from django.db import connection


class Command(BaseCommand):
    help = 'Fix production database - add missing columns'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=' * 70))
        self.stdout.write(self.style.SUCCESS('Production Database Fix'))
        self.stdout.write(self.style.SUCCESS('=' * 70))
        self.stdout.write('')
        
        # Add business_short_code column
        self.stdout.write('Adding business_short_code column to mpesa_transactions...')
        try:
            with connection.cursor() as cursor:
                cursor.execute("""
                    ALTER TABLE mpesa_transactions 
                    ADD COLUMN business_short_code VARCHAR(10) NULL
                """)
            self.stdout.write(self.style.SUCCESS('✓ Added business_short_code column'))
        except Exception as e:
            if 'Duplicate column' in str(e):
                self.stdout.write(self.style.WARNING('⊙ Column already exists'))
            else:
                self.stdout.write(self.style.ERROR(f'✗ Error: {e}'))
        
        self.stdout.write('')
        self.stdout.write(self.style.SUCCESS('=' * 70))
        self.stdout.write(self.style.SUCCESS('✓ Database fix completed!'))
        self.stdout.write(self.style.SUCCESS('=' * 70))
        self.stdout.write('')
        self.stdout.write('Test the page: /payments/unconfirmed-payments/')
        self.stdout.write('')
