# Generated by Django 4.2.18 on 2025-01-31 14:40

from django.db import migrations


def set_event_grouping(apps, schema_editor):
    # We can just deduce the grouping from the issue, because manual merging of issues has no UI yet, i.e. as it stands
    # an issue always has exactly one grouping.

    # This is slightly optimized under the assumption that in cases where there are very many events, there a orders of
    # magnitude fewer issues, so we iterate over issues and then filter events by issue, rather than iterating over
    # events and then getting the issue for each event.

    # Naive impl.:
    # Event = apps.get_model("events", "Event")
    # for event in Event.objects.all():
    #     event.grouping = event.issue.grouping_set.first()
    #     event.save()

    Event = apps.get_model("events", "Event")
    Issue = apps.get_model("issues", "Issue")
    for issue in Issue.objects.all():
        grouping = issue.grouping_set.first()
        Event.objects.filter(issue=issue).update(grouping=grouping)


class Migration(migrations.Migration):

    dependencies = [
        ("events", "0014_event_grouping"),  # This is the previous migration
        ("issues", "0002_initial"),  # Defines Issue.grouping

        # Previously, we depended on the below, but given the above that seems too restrictive.
        # ("issues", "0007_alter_turningpoint_options"),  #
    ]

    operations = [
        migrations.RunPython(set_event_grouping),
    ]
