# Generated by Django 6.0.6 on 2026-06-18 21:03

import django.db.models.deletion
from django.db import migrations, models


def backfill_related_game(apps, schema_editor):
    """Move each add-on purchase's parent link from the parent *purchase* to a
    parent *game*. For a parent bought as a multi-game bundle there is no single
    game, so use the bundle's first game (by sort_name) as the best guess."""
    Purchase = apps.get_model("games", "Purchase")
    for purchase in Purchase.objects.filter(related_purchase__isnull=False):
        parent_game = purchase.related_purchase.games.order_by("sort_name").first()
        if parent_game is not None:
            purchase.related_game = parent_game
            purchase.save(update_fields=["related_game"])


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("games", "0019_alter_filterpreset_mode"),
    ]

    operations = [
        migrations.AddField(
            model_name="purchase",
            name="related_game",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="addon_purchases",
                to="games.game",
            ),
        ),
        migrations.RunPython(backfill_related_game, noop_reverse),
        migrations.RemoveField(
            model_name="purchase",
            name="related_purchase",
        ),
    ]
