# Generated by Django 5.0 on 2024-04-10 08:38

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


children_infos = {}


def get_children_infos(apps, schema_editor):
    Page = apps.get_model("aircox", "page")
    query = Page.objects.filter(parent__isnull=False).values("pk", "parent_id", "category_id", "parent__category_id")
    children_infos.update((r["pk"], r) for r in query)


def restore_children_infos(apps, schema_editor):
    Episode = apps.get_model("aircox", "Episode")

    pks = set(children_infos.keys())
    eps = _restore_for_objs(Episode.objects.filter(pk__in=pks))
    Episode.objects.bulk_update(eps, ("parent_id", "category_id"))
    print(f">> {len(eps)} episodes restored")


def _restore_for_objs(objs):
    updated = []
    for obj in objs:
        info = children_infos.get(obj.pk)
        if info:
            obj.parent_id = info["parent_id"]
            obj.category_id = info["category_id"] or info["parent__category_id"]
            updated.append(obj)
    return updated


class Migration(migrations.Migration):
    dependencies = [
        ("aircox", "0026_alter_sound_options_remove_sound_episode_and_more"),
    ]

    operations = [
        migrations.RunPython(get_children_infos),
        migrations.RemoveField(
            model_name="page",
            name="parent",
        ),
        migrations.RemoveField(
            model_name="staticpage",
            name="parent",
        ),
        migrations.RemoveField(
            model_name="station",
            name="path",
        ),
        migrations.AddField(
            model_name="article",
            name="parent",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="%(class)s_set",
                to="aircox.page",
            ),
        ),
        migrations.AddField(
            model_name="episode",
            name="parent",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="%(class)s_set",
                to="aircox.page",
            ),
        ),
        migrations.RunPython(restore_children_infos),
    ]
