from django.db import migrations, models


def normalize_status(apps, schema_editor):
    """Repair any rows written with the interim lowercase status values
    (from migration 0018) back to the canonical capitalized lifecycle values
    the rest of the app expects. `pending_approval` was never a real `status`
    value (that lives on `approval_status`), so it maps back to Draft."""
    JobDescription = apps.get_model('jobs', 'JobDescription')
    mapping = {
        'draft': 'Draft',
        'published': 'Published',
        'closed': 'Closed',
        'pending_approval': 'Draft',
    }
    for raw, fixed in mapping.items():
        JobDescription.objects.filter(status=raw).update(status=fixed)


class Migration(migrations.Migration):

    dependencies = [
        ('jobs', '0018_alter_jobdescription_status'),
    ]

    operations = [
        migrations.AlterField(
            model_name='jobdescription',
            name='status',
            field=models.CharField(
                choices=[('Draft', 'Draft'), ('Published', 'Published'), ('Closed', 'Closed')],
                default='Draft',
                max_length=20,
            ),
        ),
        migrations.RunPython(normalize_status, migrations.RunPython.noop),
    ]
