# Generated by Django 4.0.5 on 2023-02-17 20:31

from django.db import migrations


def migrate_customer_and_organization_addresses(apps, schema_editor):
    Customer = apps.get_model("metering_billing", "Customer")
    Organization = apps.get_model("metering_billing", "Organization")
    Address = apps.get_model("metering_billing", "Address")

    # Migrate customer addresses
    for customer in Customer.objects.filter(properties__address__isnull=False):
        properties = customer.properties
        address_data = properties.pop("address", {})
        address, _ = Address.objects.get_or_create(
            organization=customer.organization,
            city=address_data.get("city"),
            country=address_data.get("country"),
            line1=address_data.get("line1"),
            line2=address_data.get("line2"),
            postal_code=address_data.get("postal_code"),
            state=address_data.get("state"),
        )
        customer.billing_address = address
        customer.shipping_address = address
        customer.save()

    # Migrate organization addresses
    for org in Organization.objects.filter(properties__address__isnull=False):
        properties = org.properties
        address_data = properties.pop("address", {})
        address, _ = Address.objects.get_or_create(
            organization=org,
            city=address_data.get("city"),
            country=address_data.get("country"),
            line1=address_data.get("line1"),
            line2=address_data.get("line2"),
            postal_code=address_data.get("postal_code"),
            state=address_data.get("state"),
        )
        org.address = address
        org.properties = properties
        org.save()


class Migration(migrations.Migration):
    dependencies = [
        ("metering_billing", "0185_remove_customer_integrations_and_more"),
    ]

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