# Generated by Django 3.2.9 on 2021-11-06 18:53

import logging

from django.db import migrations, models
from django.db.models import Q, deletion

from netbox_dns.models import RecordTypeChoices


def cleanup_disable_ptr(apps, schema_editor):
    logger = logging.getLogger("django")

    Record = apps.get_model("netbox_dns", "Record")

    unique_ptr_qs = Q(
        Q(disable_ptr=False),
        Q(Q(type=RecordTypeChoices.A) | Q(type=RecordTypeChoices.AAAA)),
    )

    for record in Record.objects.filter(unique_ptr_qs):
        logger.warning(
            "Disabling PTR generation for record %s:%s in zone %s",
            record.type,
            record.name,
            record.zone.name,
        )
        record.disable_ptr = True
        record.save()


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("netbox_dns", "0003_soa_managed_records"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="nameserver",
            options={"ordering": ("name",)},
        ),
        migrations.AlterModelOptions(
            name="record",
            options={"ordering": ("zone", "name", "type", "value")},
        ),
        migrations.AddField(
            model_name="record",
            name="disable_ptr",
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name="record",
            name="ptr_record",
            field=models.OneToOneField(
                blank=True,
                null=True,
                on_delete=deletion.SET_NULL,
                related_name="address_record",
                to="netbox_dns.record",
            ),
        ),
        migrations.RunPython(cleanup_disable_ptr),
        migrations.AddConstraint(
            model_name="record",
            constraint=models.UniqueConstraint(
                condition=Q(
                    Q(("disable_ptr", False)),
                    Q(
                        ("type", RecordTypeChoices.A),
                        ("type", RecordTypeChoices.AAAA),
                        _connector="OR",
                    ),
                ),
                fields=("type", "value"),
                name="unique_pointer_for_address",
            ),
        ),
    ]
