# Migration: restrict product_type choices to biashara and logbook only
# Removes Boost, Boost Plus, Mwamba, Imara from the choices list

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('loans', '0027_loan_approved_by_loan_created_by_loan_disbursed_by_and_more'),
    ]

    operations = [
        # Update any existing rows that have old product_type values
        migrations.RunSQL(
            sql="""
                UPDATE loan_products
                SET product_type = 'biashara'
                WHERE product_type IN ('boost', 'boost_plus', 'mwamba', 'imara', 'personal',
                                       'business', 'salary', 'emergency', 'asset', '')
                  AND name LIKE '%Biashara%';
            """,
            reverse_sql=migrations.RunSQL.noop,
        ),
        migrations.RunSQL(
            sql="""
                UPDATE loan_products
                SET product_type = 'logbook'
                WHERE product_type IN ('boost', 'boost_plus', 'mwamba', 'imara', 'personal',
                                       'business', 'salary', 'emergency', 'asset', '')
                  AND name LIKE '%Log%';
            """,
            reverse_sql=migrations.RunSQL.noop,
        ),
        migrations.RunSQL(
            sql="""
                UPDATE loan_products
                SET product_type = 'biashara', is_active = 0
                WHERE product_type NOT IN ('biashara', 'logbook');
            """,
            reverse_sql=migrations.RunSQL.noop,
        ),
        # Update the field choices in Django's state
        migrations.AlterField(
            model_name='loanproduct',
            name='product_type',
            field=models.CharField(
                max_length=20,
                choices=[
                    ('biashara', 'Biashara Loan'),
                    ('logbook', 'Log Book Loan'),
                ],
            ),
        ),
    ]
