# Generated by Django 4.2.16 on 2024-10-29 15:03

from django.db import migrations


def migrate_autocheckin(apps, schema_editor):
    CheckinList = apps.get_model("pretixbase", "CheckinList")
    AutoCheckinRule = apps.get_model("autocheckin", "AutoCheckinRule")

    for cl in CheckinList.objects.filter(auto_checkin_sales_channels__isnull=False).select_related("event", "event__organizer"):
        sales_channels = cl.auto_checkin_sales_channels.all()
        all_sales_channels = cl.event.organizer.sales_channels.all()

        if "pretix.plugins.autocheckin" not in cl.event.plugins:
            cl.event.plugins = cl.event.plugins + ",pretix.plugins.autocheckin"
            cl.event.save()

        r = AutoCheckinRule.objects.get_or_create(
            list=cl,
            event=cl.event,
            all_products=True,
            all_payment_methods=True,
            defaults=dict(
                mode="placed",
                all_sales_channels=len(sales_channels) == len(all_sales_channels),
            )
        )[0]
        if len(sales_channels) != len(all_sales_channels):
            r.limit_sales_channels.set(sales_channels)


class Migration(migrations.Migration):

    dependencies = [
        ("pretixbase", "0272_printlog"),
        ("autocheckin", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(
            migrate_autocheckin,
            migrations.RunPython.noop,
        ),
        migrations.RemoveField(
            model_name="checkinlist",
            name="auto_checkin_sales_channels",
        ),
    ]
