from django.db import migrations


def copied_jds_to_draft(apps, schema_editor):
    """Copied JDs must be Drafts. Copies are identified by their CREATED audit-log
    entry ('Copied from JD #…'); only Published ones are moved back to Draft."""
    JobDescription = apps.get_model("jobs", "JobDescription")
    JDAuditLog = apps.get_model("jobs", "JDAuditLog")

    copied_ids = (
        JDAuditLog.objects.filter(action="CREATED", changes__startswith="Copied from JD")
        .exclude(job_id=None)
        .values_list("job_id", flat=True)
    )
    JobDescription.objects.filter(id__in=list(copied_ids), status="Published").update(
        status="Draft"
    )


class Migration(migrations.Migration):

    dependencies = [
        ("jobs", "0014_alter_jobdescription_options"),
    ]

    operations = [
        migrations.RunPython(copied_jds_to_draft, migrations.RunPython.noop),
    ]
