# Generated by Django 3.1.6 on 2021-02-12 04:26

from django.db import migrations


def registration_to_invoice(apps, schema_editor):
    VoucherUse = apps.get_model("vouchers", "VoucherUse")
    db_alias = schema_editor.connection.alias

    # Cannot keep VoucherUse objects that cannot be linked to a specific
    # invoice.
    VoucherUse.objects.using(db_alias).filter(
        registration__isnull=True, invoice__isnull=True
    ).delete()

    objects = VoucherUse.objects.using(db_alias).filter(
        invoice__isnull=True, registration__isnull=False
    )
    for obj in objects:
        obj.invoice = obj.registration.invoice
        obj.save()


def invoice_to_registration(apps, schema_editor):
    VoucherUse = apps.get_model("vouchers", "VoucherUse")
    db_alias = schema_editor.connection.alias
    objects = VoucherUse.objects.using(db_alias).filter(
        invoice__isnull=False, invoice__registration__isnull=False,
        registration__isnull=True
    )
    for obj in objects:
        obj.registration = getattr(obj.invoice, 'registration', None)
        obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ('vouchers', '0013_auto_20210211_2326'),
    ]

    operations = [
        migrations.RunPython(registration_to_invoice, invoice_to_registration)
    ]
