# Generated by Django 5.2.9 on 2026-02-17 04:24

from django.db import migrations, models


def dedup_addresses(apps, schema_editor):
    """Merge duplicate RIRAddress rows before adding unique constraint."""
    RIRAddress = apps.get_model("netbox_rir_manager", "RIRAddress")
    dupes = (
        RIRAddress.objects.values("street_address", "city", "state_province", "postal_code", "country")
        .annotate(cnt=models.Count("id"))
        .filter(cnt__gt=1)
    )
    for group in dupes:
        addrs = list(
            RIRAddress.objects.filter(
                street_address=group["street_address"],
                city=group["city"],
                state_province=group["state_province"],
                postal_code=group["postal_code"],
                country=group["country"],
            ).order_by("pk")
        )
        keeper = addrs[0]
        for dup in addrs[1:]:
            # Re-point all FKs to the keeper
            for related in ("rir_organizations", "rir_contacts", "rir_customers"):
                getattr(dup, related).update(address=keeper)
            dup.delete()


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("dcim", "0225_gfk_indexes"),
        ("extras", "0134_owner"),
        ("netbox_rir_manager", "0014_riraddress_refactor"),
    ]

    operations = [
        migrations.RunPython(dedup_addresses, migrations.RunPython.noop),
        migrations.AddConstraint(
            model_name="riraddress",
            constraint=models.UniqueConstraint(
                fields=("street_address", "city", "state_province", "postal_code", "country"),
                name="unique_rir_address",
            ),
        ),
    ]
