# Generated by Django 4.2.11 on 2025-05-12 16:28

from django.db import migrations


def deduplicate_networkfacility(apps, schema_editor):
    """
    Find and deduplicate NetworkFacility entries that would violate the new
    unique_together constraint (net, fac).

    Keep the most recently updated entry for each (net, fac) pair.
    """
    NetworkFacility = apps.get_model("django_peeringdb", "NetworkFacility")

    # Get all NetworkFacility objects
    all_netfacs = NetworkFacility.handleref.all()

    # Track seen (net_id, fac_id) pairs
    seen = {}
    to_delete = []

    for netfac in all_netfacs:
        pair = (netfac.net_id, netfac.fac_id)

        if pair in seen:
            # Compare with the existing entry
            existing = seen[pair]

            # Keep the most recently updated entry
            if netfac.updated > existing.updated:
                to_delete.append(existing)
                seen[pair] = netfac
            else:
                to_delete.append(netfac)
        else:
            seen[pair] = netfac

    # Delete duplicates
    for netfac in to_delete:
        netfac.delete()


class Migration(migrations.Migration):
    dependencies = [
        ("django_peeringdb", "0036_networkixlan_net_side_networkixlan_ix_side"),
    ]

    operations = [
        # First run the deduplication function
        migrations.RunPython(
            deduplicate_networkfacility, reverse_code=migrations.RunPython.noop
        ),
        # Then alter the unique_together constraint
        migrations.AlterUniqueTogether(
            name="networkfacility",
            unique_together={("net", "fac")},
        ),
        # Finally remove the local_asn field
        migrations.RemoveField(
            model_name="networkfacility",
            name="local_asn",
        ),
    ]
