# Generated migration for Grazuri loan product fields
# Adds gl_code and grazuri_account_type to LoanProduct
# Also adds biashara and logbook to PRODUCT_TYPES choices

from django.db import migrations, models


def check_and_add_fields(apps, schema_editor):
    """Check if columns exist before adding them"""
    from django.db import connection
    
    with connection.cursor() as cursor:
        # Check if gl_code column exists
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'loan_products' 
            AND COLUMN_NAME = 'gl_code'
        """)
        gl_code_exists = cursor.fetchone()[0] > 0
        
        # Check if grazuri_account_type column exists
        cursor.execute("""
            SELECT COUNT(*) 
            FROM information_schema.COLUMNS 
            WHERE TABLE_SCHEMA = DATABASE() 
            AND TABLE_NAME = 'loan_products' 
            AND COLUMN_NAME = 'grazuri_account_type'
        """)
        grazuri_account_type_exists = cursor.fetchone()[0] > 0
        
        # Add gl_code if it doesn't exist
        if not gl_code_exists:
            cursor.execute("""
                ALTER TABLE loan_products 
                ADD COLUMN gl_code VARCHAR(20) NOT NULL DEFAULT ''
            """)
        
        # Add grazuri_account_type if it doesn't exist
        if not grazuri_account_type_exists:
            cursor.execute("""
                ALTER TABLE loan_products 
                ADD COLUMN grazuri_account_type VARCHAR(5) NOT NULL DEFAULT ''
            """)


class Migration(migrations.Migration):

    dependencies = [
        ('loans', '0025_add_grazuri_foreign_key_models'),
    ]

    operations = [
        migrations.RunPython(check_and_add_fields, migrations.RunPython.noop),
        migrations.AlterField(
            model_name='loanproduct',
            name='product_type',
            field=models.CharField(
                choices=[
                    ('biashara', 'Biashara Loan'),
                    ('logbook', 'Log Book Loan'),
                ],
                max_length=20,
            ),
        ),
    ]
