# Generated by Django 3.2.13 on 2022-06-07 11:23

from django.db import migrations
from django.db.models import Q


def forwards(apps, schema_editor):
    PaymentMethod = apps.get_model("checkout", "PaymentMethod")
    Surcharge = apps.get_model("checkout", "Surcharge")
    PercentageSurcharge = apps.get_model("checkout", "PercentageSurcharge")
    FixedSurcharge = apps.get_model("checkout", "FixedSurcharge")

    Surcharge.objects.filter(
        Q(is_percentage=True, percentage__isnull=True)
        | Q(is_percentage=False, excl_tax__isnull=True)
        | Q(is_percentage=False, incl_tax__isnull=True)
    ).delete()

    for surcharge in Surcharge.objects.filter(is_percentage=True):
        new_surcharge, _ = PercentageSurcharge.objects.get_or_create(
            code=surcharge.code,
            name=surcharge.name,
            percentage=surcharge.percentage,
            include_shipping_charges=surcharge.include_shipping_charges,
        )
        payment_methods = PaymentMethod.objects.filter(surcharge=surcharge)
        if payment_methods:
            new_surcharge.payment_method.add(*payment_methods)

    for surcharge in Surcharge.objects.filter(is_percentage=False):
        new_surcharge, _ = FixedSurcharge.objects.get_or_create(
            code=surcharge.code,
            name=surcharge.name,
            excl_tax=surcharge.excl_tax,
            incl_tax=surcharge.incl_tax,
        )
        payment_methods = PaymentMethod.objects.filter(surcharge=surcharge)
        if payment_methods:
            new_surcharge.payment_method.add(*payment_methods)



class Migration(migrations.Migration):

    dependencies = [
        ('checkout', '0012_fixedsurcharge_percentagesurcharge'),
    ]

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