# Generated by Django 3.2.24 on 2024-02-12 19:57

from django.db import migrations
from django.db.models.functions import Length

from nautobot.ipam.choices import IPAddressVersionChoices
from nautobot.ipam.constants import IPV4_BYTE_LENGTH, IPV6_BYTE_LENGTH


def fixup_null_ip_version_values(apps, schema):
    IPAddress = apps.get_model("ipam", "IPAddress")
    Prefix = apps.get_model("ipam", "Prefix")

    ips_to_fixup = IPAddress.objects.filter(ip_version__isnull=True).annotate(host_length=Length("host"))
    ips_to_fixup.filter(host_length=IPV4_BYTE_LENGTH).update(ip_version=IPAddressVersionChoices.VERSION_4)
    ips_to_fixup.filter(host_length=IPV6_BYTE_LENGTH).update(ip_version=IPAddressVersionChoices.VERSION_6)

    prefixes_to_fixup = Prefix.objects.filter(ip_version__isnull=True).annotate(network_length=Length("network"))
    prefixes_to_fixup.filter(network_length=IPV4_BYTE_LENGTH).update(ip_version=IPAddressVersionChoices.VERSION_4)
    prefixes_to_fixup.filter(network_length=IPV6_BYTE_LENGTH).update(ip_version=IPAddressVersionChoices.VERSION_6)


class Migration(migrations.Migration):
    dependencies = [
        ("ipam", "0042_remove_location_from_vlan_and_prefix"),
    ]

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