# Generated by Django 4.2.17 on 2025-09-08 08:14
from django.core.cache import cache
from django.db import migrations


def set_invoice_period(apps, schema_editor):
    EventSettingsStore = apps.get_model("pretixbase", "Event_SettingsStore")
    ev_seen = set()
    insert_queue = []
    flush_queue = []

    def store():
        EventSettingsStore.objects.bulk_create(
            insert_queue,
            update_conflicts=True,
            update_fields=["value"],
            unique_fields=["object", "key"],
        )
        cache.delete_many(flush_queue)
        flush_queue.clear()
        insert_queue.clear()

    # Existing events that use pretix-zugferd and have explicitly disabled delivery dates
    for setting in EventSettingsStore.objects.filter(key="zugferd_include_delivery_date", value="False"):
        flush_queue.append("hierarkey_{}_{}".format("event", setting.object_id))
        insert_queue.append(
            EventSettingsStore(
                object_id=setting.object_id,
                key="invoice_period",
                value="invoice_date",
            )
        )
        ev_seen.add(setting.object_id)

        if len(insert_queue) > 1000:
            store()

    # Existing events that previously hid their date on invoices
    for setting in EventSettingsStore.objects.filter(key="show_dates_on_frontpage", value="False"):
        if setting.object_id in ev_seen:
            continue

        flush_queue.append("hierarkey_{}_{}".format("event", setting.object_id))
        insert_queue.append(
            EventSettingsStore(
                object_id=setting.object_id,
                key="invoice_period",
                value="auto_no_event",
            )
        )

        if len(insert_queue) > 1000:
            store()

    store()


class Migration(migrations.Migration):
    dependencies = [
        ("pretixbase", "0288_invoice_transmission"),
    ]

    operations = [
        migrations.RenameField(
            model_name="invoiceline",
            old_name="event_date_to",
            new_name="period_end",
        ),
        migrations.RenameField(
            model_name="invoiceline",
            old_name="event_date_from",
            new_name="period_start",
        ),
        migrations.RunPython(
            set_invoice_period,
            migrations.RunPython.noop,
        )
    ]
