"""Repoint ProgrammeCourseLink from the retired REP LMS to Moodle course ids.

The REP learning platform is being replaced by Moodle, so the PROTECT FK into
``rep_courses.Course`` is converted to a plain ``moodle_course_id`` string (plus
a denormalised ``course_title``). Existing links carry the old REP course pk into
``moodle_course_id`` as a legacy marker; operators re-link them to real Moodle
courses. Runs while ``rep_courses`` still exists so the FK removal is clean.
"""
from django.db import migrations, models


def course_fk_to_moodle_id(apps, schema_editor):
    ProgrammeCourseLink = apps.get_model("smehub_incubation", "ProgrammeCourseLink")
    # ``course`` is a plain integer column (formerly a FK into the retired
    # rep_courses.course); carry its value into moodle_course_id as a legacy marker.
    for row in ProgrammeCourseLink.objects.all():
        ProgrammeCourseLink.objects.filter(pk=row.pk).update(
            moodle_course_id=str(row.course) if row.course is not None else ""
        )


class Migration(migrations.Migration):

    dependencies = [
        ("smehub_incubation", "0012_programme_judges_programme_reminder_days_before_and_more"),
    ]

    operations = [
        migrations.RemoveConstraint(
            model_name="programmecourselink",
            name="uniq_smehub_programme_course",
        ),
        migrations.AddField(
            model_name="programmecourselink",
            name="moodle_course_id",
            field=models.CharField(
                default="", help_text="Moodle course id (mdl_course.id).", max_length=64
            ),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="programmecourselink",
            name="course_title",
            field=models.CharField(
                blank=True,
                help_text="Denormalised Moodle course name for display.",
                max_length=255,
            ),
        ),
        migrations.RunPython(course_fk_to_moodle_id, migrations.RunPython.noop),
        migrations.RemoveField(
            model_name="programmecourselink",
            name="course",
        ),
        migrations.AddConstraint(
            model_name="programmecourselink",
            constraint=models.UniqueConstraint(
                fields=["programme", "moodle_course_id"],
                name="uniq_smehub_programme_course",
            ),
        ),
    ]
