from django.db import migrations, models


def backfill_vehicle_types(apps, schema_editor):
    Vehicle = apps.get_model('accounts', 'Vehicle')
    for vehicle in Vehicle.objects.all().iterator():
        primary = (vehicle.vehicle_type or '').strip()
        types = vehicle.vehicle_types if isinstance(vehicle.vehicle_types, list) else []
        cleaned = [str(t).strip() for t in types if str(t).strip()]
        if cleaned:
            continue
        if primary:
            vehicle.vehicle_types = [primary]
            vehicle.save(update_fields=['vehicle_types'])


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0029_rename_accounts_pa_email_6ff4e0_idx_accounts_pa_email_fe78d7_idx_and_more'),
    ]

    operations = [
        migrations.AddField(
            model_name='vehicle',
            name='vehicle_types',
            field=models.JSONField(
                blank=True,
                default=list,
                help_text='All vehicle types this unit can serve; vehicle_type is kept as the primary (first) entry.',
            ),
        ),
        migrations.RunPython(backfill_vehicle_types, migrations.RunPython.noop),
    ]
