# Generated by Django 4.2.17 on 2025-03-28 09:19
from django.core.cache import cache
from django.db import migrations, models
from django.db.models import Count, Exists, OuterRef


def set_default_tax_rate(app, schema_editor):
    Event = app.get_model('pretixbase', 'Event')
    Event_SettingsStore = app.get_model('pretixbase', 'Event_SettingsStore')
    TaxRule = app.get_model('pretixbase', 'TaxRule')

    # Handling of events with tax_rate_default set
    for s in Event_SettingsStore.objects.filter(key="tax_rate_default").iterator():
        updated = TaxRule.objects.filter(pk=s.value, event_id=s.object_id).update(default=True)
        if updated:
            # Delete deprecated settings key
            s.delete()

            # The default for new events is tax_rule_cancellation=none, but since we do not change behaviour
            # for existing events without warning, we create a settings entry that matches the old behaviour.
            Event_SettingsStore.objects.get_or_create(
                object_id=s.object_id,
                key="tax_rule_cancellation",
                defaults={"value": "default"},
            )

            # We do not need to set tax_rule_payment here since "default" is the default

            cache.delete('hierarkey_{}_{}'.format('event', s.object_id))

    # Handling of events with tax_rate_default not set
    for e in Event.objects.only("pk").exclude(Exists(TaxRule.objects.filter(default=True, event_id=OuterRef("pk")))).iterator():
        fav_tax_rules = e.tax_rules.annotate(c=Count("item")).order_by("-c", "pk")[:1]
        if fav_tax_rules:
            fav_tax_rules[0].default = True
            fav_tax_rules[0].save()

        # Previously, no tax rule was set for payments, so keep it this way
        Event_SettingsStore.objects.get_or_create(
            object=e,
            key="tax_rule_payment",
            defaults={"value": "none"},
        )
        cache.delete('hierarkey_{}_{}'.format('event', e.pk))

        # We do not need to set tax_rule_cancellation, as "none" is the new system default


class Migration(migrations.Migration):

    dependencies = [
        ("pretixbase", "0282_taxrule_default"),
    ]

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