# Generated by Django 4.2.26 on 2025-11-24 11:32

from django.db import migrations, models


def reverse(apps, schema_editor):
    ReusableMedium = apps.get_model('pretixbase', 'ReusableMedium')

    qs = ReusableMedium.linked_orderpositions.through.objects
    objs = []
    # get last added orderposition from linked_orderpositions
    for rm_id, op_id in qs.filter(id__in=qs.values("reusablemedium_id").annotate(max_id=models.Max('id')).values('max_id')).values_list("reusablemedium_id", "orderposition_id"):
        obj = ReusableMedium(
            id=rm_id,
            linked_orderposition_id=op_id,
        )
        objs.append(obj)

    ReusableMedium.objects.bulk_update(objs, ['linked_orderposition_id'])


class Migration(migrations.Migration):

    dependencies = [
        ("pretixbase", "0300_add_reusablemedium_label"),
    ]

    operations = [
        # according to the docs, UPDATE FROM should run similarly on sqlite and postgres, but I could not get it to work
        # so roll back the data migration with code before deleting data from through-table in 0297
        migrations.RunPython(migrations.RunPython.noop, reverse),
        migrations.RemoveField(
            model_name="reusablemedium",
            name="linked_orderposition",
        ),
        # change related_name for new ManyToManyField to previously used linked_media
        migrations.AlterField(
            model_name="reusablemedium",
            name="linked_orderpositions",
            field=models.ManyToManyField(
                related_name="linked_media", to="pretixbase.orderposition"
            ),
        ),
    ]
