from django.db import migrations


def copy_subproduct_homepage_flags(apps, schema_editor):
    SubProduct = apps.get_model("products", "SubProduct")
    for sub in (
        SubProduct.objects.filter(show_on_homepage=True)
        .select_related("main_product")
        .order_by("homepage_order", "order")
    ):
        main = sub.main_product
        if not main.show_on_homepage:
            main.show_on_homepage = True
            main.homepage_order = sub.homepage_order
            main.save(update_fields=["show_on_homepage", "homepage_order"])


class Migration(migrations.Migration):

    dependencies = [
        ("products", "0011_mainproduct_homepage_order_and_more"),
    ]

    operations = [
        migrations.RunPython(copy_subproduct_homepage_flags, migrations.RunPython.noop),
    ]
