from django.db import migrations, models


def backfill_trip_status_records(apps, schema_editor):
    Trip = apps.get_model('core', 'Trip')
    TripStatusRecord = apps.get_model('core', 'TripStatusRecord')
    for trip in Trip.objects.all().iterator():
        if TripStatusRecord.objects.filter(trip_id=trip.id).exists():
            continue
        TripStatusRecord.objects.create(
            trip_id=trip.id,
            status=trip.status,
            recorded_at=trip.created_at,
        )


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0007_notification'),
    ]

    operations = [
        migrations.CreateModel(
            name='TripStatusRecord',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('status', models.CharField(choices=[('DRAFT', 'Draft'), ('PUBLISHED', 'Published'), ('ASSIGNED', 'Assigned'), ('EN_ROUTE', 'En Route to Pickup'), ('ARRIVED_PICKUP', 'Arrived at Pickup'), ('LOADED', 'Loaded'), ('IN_TRANSIT', 'In Transit'), ('ARRIVED_DELIVERY', 'Arrived at Delivery'), ('DELIVERED', 'Delivered'), ('COMPLETED', 'Completed'), ('CLOSED', 'Closed')], max_length=20)),
                ('recorded_at', models.DateTimeField(auto_now_add=True)),
                ('trip', models.ForeignKey(on_delete=models.deletion.CASCADE, related_name='status_records', to='core.trip')),
            ],
            options={
                'ordering': ['recorded_at', 'id'],
            },
        ),
        migrations.RunPython(backfill_trip_status_records, migrations.RunPython.noop),
    ]
