# Generated by Django 3.2.2 on 2021-11-08 07:51

from django.db import migrations, models
from django.db.models import Count, OuterRef, Subquery
from django.db.models.functions import Coalesce


def fill_is_bundled(apps, schema_editor):
    # We cannot really know if a position was bundled or an add-on, but we can at least guess
    ItemBundle = apps.get_model("pretixbase", "ItemBundle")
    OrderPosition = apps.get_model("pretixbase", "OrderPosition")

    for ib in ItemBundle.objects.iterator():
        OrderPosition.all.alias(
            pos_earlier=Coalesce(Subquery(
                OrderPosition.all.filter(
                    canceled=False,
                    addon_to=OuterRef('addon_to'),
                    item=ib.bundled_item,
                    variation=ib.bundled_variation,
                    positionid__lt=OuterRef('positionid'),
                ).values('addon_to').order_by().annotate(c=Count('*')).values('c'),
                output_field=models.IntegerField()
            ), 0)
        ).filter(
            canceled=False,
            addon_to__item=ib.base_item,
            item=ib.bundled_item,
            variation=ib.bundled_variation,
            pos_earlier__lt=ib.count,
        ).update(
            is_bundled=True
        )


class Migration(migrations.Migration):
    dependencies = [
        ('pretixbase', '0203_orderposition_is_bundled'),
    ]

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