"""Sever AlumniHandoff's FK into the retired REP LMS (``rep_courses.Enrolment``).

The REP learning platform is being replaced by Moodle, so the cross-app FK is
converted to a plain string ``enrolment_ref`` (preserving the upstream id) and
the FK is dropped. Runs while ``rep_courses`` still exists, so the removal is
clean; afterwards nothing in ``rep_career`` references ``rep_courses``.
"""
from django.db import migrations, models


def copy_enrolment_to_ref(apps, schema_editor):
    AlumniHandoff = apps.get_model("rep_career", "AlumniHandoff")
    # ``enrolment`` is a plain nullable integer column (formerly a FK into the
    # retired rep_courses.enrolment); carry its value into enrolment_ref.
    for row in AlumniHandoff.objects.exclude(enrolment=None).only("id", "enrolment"):
        AlumniHandoff.objects.filter(pk=row.pk).update(enrolment_ref=str(row.enrolment))


class Migration(migrations.Migration):

    dependencies = [
        ("rep_career", "0010_job_country_qualification_saved_job"),
    ]

    operations = [
        migrations.AddField(
            model_name="alumnihandoff",
            name="enrolment_ref",
            field=models.CharField(
                blank=True,
                help_text="Upstream enrolment/completion id (legacy REP enrolment pk or Moodle completion ref).",
                max_length=64,
            ),
        ),
        migrations.RunPython(copy_enrolment_to_ref, migrations.RunPython.noop),
        migrations.RemoveField(
            model_name="alumnihandoff",
            name="enrolment",
        ),
    ]
