# Generated by Django 5.2.9 on 2026-01-04 23:11

import apps.sigils.fields
import django.db.models.deletion
from django.core.management.color import no_style
from django.conf import settings
from django.db import migrations, models
from django.db.models import F


def reset_sequences(models, schema_editor):
    sql_statements = schema_editor.connection.ops.sequence_reset_sql(
        no_style(), models
    )
    if sql_statements:
        with schema_editor.connection.cursor() as cursor:
            for statement in sql_statements:
                cursor.execute(statement)


def migrate_node_manager_credentials(apps, schema_editor):
    NodeManager = apps.get_model("nodes", "NodeManager")
    DNSProviderCredential = apps.get_model("dns", "DNSProviderCredential")
    GoDaddyDNSRecord = apps.get_model("dns", "GoDaddyDNSRecord")

    for manager in NodeManager.objects.all():
        DNSProviderCredential.objects.update_or_create(
            pk=manager.pk,
            defaults={
                "provider": manager.provider,
                "api_key": manager.api_key,
                "api_secret": manager.api_secret,
                "customer_id": manager.customer_id,
                "default_domain": manager.default_domain,
                "use_sandbox": manager.use_sandbox,
                "is_enabled": manager.is_enabled,
                "user_id": getattr(manager, "user_id", None),
                "group_id": getattr(manager, "group_id", None),
                "avatar_id": getattr(manager, "avatar_id", None),
                "is_seed_data": manager.is_seed_data,
                "is_user_data": manager.is_user_data,
            },
        )

    GoDaddyDNSRecord.objects.filter(node_manager_id__isnull=False).update(
        credentials_id=F("node_manager_id")
    )

    reset_sequences([DNSProviderCredential], schema_editor)


def reverse_node_manager_credentials(apps, schema_editor):
    NodeManager = apps.get_model("nodes", "NodeManager")
    DNSProviderCredential = apps.get_model("dns", "DNSProviderCredential")
    GoDaddyDNSRecord = apps.get_model("dns", "GoDaddyDNSRecord")

    for credential in DNSProviderCredential.objects.all():
        NodeManager.objects.update_or_create(
            pk=credential.pk,
            defaults={
                "provider": credential.provider,
                "api_key": credential.api_key,
                "api_secret": credential.api_secret,
                "customer_id": credential.customer_id,
                "default_domain": credential.default_domain,
                "use_sandbox": credential.use_sandbox,
                "is_enabled": credential.is_enabled,
                "user_id": getattr(credential, "user_id", None),
                "group_id": getattr(credential, "group_id", None),
                "avatar_id": getattr(credential, "avatar_id", None),
                "is_seed_data": credential.is_seed_data,
                "is_user_data": credential.is_user_data,
            },
        )

    GoDaddyDNSRecord.objects.filter(credentials_id__isnull=False).update(
        node_manager_id=F("credentials_id")
    )

    reset_sequences([NodeManager], schema_editor)


class Migration(migrations.Migration):

    dependencies = [
        ("chats", "0003_initial"),
        ("dns", "0002_initial"),
        ("groups", "0002_initial"),
        ("nodes", "0011_netmessage_expires_at"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name="DNSProviderCredential",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("is_seed_data", models.BooleanField(default=False, editable=False)),
                ("is_user_data", models.BooleanField(default=False, editable=False)),
                ("is_deleted", models.BooleanField(default=False, editable=False)),
                (
                    "provider",
                    models.CharField(
                        choices=[("godaddy", "GoDaddy")],
                        default="godaddy",
                        max_length=20,
                    ),
                ),
                (
                    "api_key",
                    apps.sigils.fields.SigilShortAutoField(
                        help_text="API key issued by the DNS provider.",
                        max_length=255,
                        verbose_name="API key",
                    ),
                ),
                (
                    "api_secret",
                    apps.sigils.fields.SigilShortAutoField(
                        help_text="API secret issued by the DNS provider.",
                        max_length=255,
                        verbose_name="API secret",
                    ),
                ),
                (
                    "customer_id",
                    apps.sigils.fields.SigilShortAutoField(
                        blank=True,
                        help_text="Optional GoDaddy customer identifier for the account.",
                        max_length=100,
                        verbose_name="Customer ID",
                    ),
                ),
                (
                    "default_domain",
                    apps.sigils.fields.SigilShortAutoField(
                        blank=True,
                        help_text="Fallback domain when records omit one.",
                        max_length=253,
                    ),
                ),
                (
                    "use_sandbox",
                    models.BooleanField(
                        default=False,
                        help_text="Use the GoDaddy OTE (test) environment.",
                    ),
                ),
                (
                    "is_enabled",
                    models.BooleanField(
                        default=True,
                        help_text="Disable to prevent deployments with this manager.",
                    ),
                ),
                (
                    "avatar",
                    models.ForeignKey(
                        blank=True,
                        help_text="Avatar that owns this profile when not linked directly to a user or group.",
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="+",
                        to="chats.chatavatar",
                    ),
                ),
                (
                    "group",
                    models.OneToOneField(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="+",
                        to="groups.securitygroup",
                    ),
                ),
                (
                    "user",
                    models.OneToOneField(
                        blank=True,
                        null=True,
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="+",
                        to=settings.AUTH_USER_MODEL,
                    ),
                ),
            ],
            options={
                "verbose_name": "DNS Credential",
                "verbose_name_plural": "DNS Credentials",
            },
        ),
        migrations.AddField(
            model_name="godaddydnsrecord",
            name="credentials",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="dns_records",
                to="dns.dnsprovidercredential",
            ),
        ),
        migrations.RunPython(
            migrate_node_manager_credentials, reverse_node_manager_credentials
        ),
        migrations.RemoveField(
            model_name="godaddydnsrecord",
            name="node_manager",
        ),
    ]
