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


def set_custom_page_section_item_page(apps, schema_editor):
    CustomPageSectionItem = apps.get_model("pages", "CustomPageSectionItem")
    for item in CustomPageSectionItem.objects.select_related("section").iterator():
        item.page_id = item.section.page_id
        item.save(update_fields=["page_id"])


class Migration(migrations.Migration):

    dependencies = [
        ("pages", "0010_homepagesectionitem_url_and_more"),
    ]

    operations = [
        migrations.AlterField(
            model_name="aboutsectionitem",
            name="url",
            field=models.CharField(
                blank=True,
                help_text="Optional link; makes this item clickable.",
                max_length=300,
            ),
        ),
        migrations.AddField(
            model_name="custompagesectionitem",
            name="page",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="section_items",
                to="pages.custompage",
            ),
        ),
        migrations.RunPython(set_custom_page_section_item_page, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="custompagesectionitem",
            name="page",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="section_items",
                to="pages.custompage",
            ),
        ),
    ]
