"""
Add a hardcoded ``status = "active"`` IPFabricTransformField to **every**
Device Transform Map (default ungrouped map and all group clones).
"""
from django.db import migrations


def add_status_field(apps, schema_editor):
    ContentType = apps.get_model("contenttypes", "ContentType")
    IPFabricTransformMap = apps.get_model("ipfabric_netbox", "IPFabricTransformMap")
    IPFabricTransformField = apps.get_model("ipfabric_netbox", "IPFabricTransformField")

    device_ct = ContentType.objects.filter(app_label="dcim", model="device").first()
    if not device_ct:
        return

    for device_map in IPFabricTransformMap.objects.filter(target_model=device_ct):
        IPFabricTransformField.objects.get_or_create(
            transform_map=device_map,
            target_field="status",
            defaults={
                "source_field": "hostname",
                "coalesce": False,
                "template": "active",
            },
        )


def remove_status_field(apps, schema_editor):
    ContentType = apps.get_model("contenttypes", "ContentType")
    IPFabricTransformField = apps.get_model("ipfabric_netbox", "IPFabricTransformField")

    device_ct = ContentType.objects.filter(app_label="dcim", model="device").first()
    if not device_ct:
        return

    IPFabricTransformField.objects.filter(
        transform_map__target_model=device_ct,
        target_field="status",
        template="active",
    ).delete()


class Migration(migrations.Migration):
    dependencies = [
        ("ipfabric_netbox", "0032_add_custom_fields_to_transform_maps"),
    ]

    operations = [
        migrations.RunPython(add_status_field, remove_status_field),
    ]
