# Generated by Django 4.2.27 on 2026-02-25 00:00

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

EVE_SDE_REGION_MODEL = getattr(
    settings, "AACAMPAIGN_SDE_REGION_MODEL", "eve_sde.Region"
)
EVE_SDE_CONSTELLATION_MODEL = getattr(
    settings, "AACAMPAIGN_SDE_CONSTELLATION_MODEL", "eve_sde.Constellation"
)
EVE_SDE_SOLAR_SYSTEM_MODEL = getattr(
    settings, "AACAMPAIGN_SDE_SOLAR_SYSTEM_MODEL", "eve_sde.SolarSystem"
)


def _expected_m2m_column(apps, model_label):
    app_label, model_name = model_label.split(".")
    model = apps.get_model(app_label, model_name)
    return f"{model._meta.model_name}_id"


def _rename_m2m_column(schema_editor, table, expected_column):
    connection = schema_editor.connection
    quote_name = schema_editor.quote_name

    with connection.cursor() as cursor:
        try:
            description = connection.introspection.get_table_description(cursor, table)
        except Exception:
            return
        columns = [col.name for col in description]

    if expected_column in columns:
        return

    candidates = [col for col in columns if col.endswith("_id") and col != "campaign_id"]
    if len(candidates) != 1:
        return

    old_column = candidates[0]

    if connection.vendor == "mysql":
        with connection.cursor() as cursor:
            cursor.execute(
                """
                SELECT CONSTRAINT_NAME
                FROM information_schema.KEY_COLUMN_USAGE
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = %s
                  AND COLUMN_NAME = %s
                  AND REFERENCED_TABLE_NAME IS NOT NULL
                """,
                [table, old_column],
            )
            for (constraint_name,) in cursor.fetchall():
                schema_editor.execute(
                    f"ALTER TABLE {quote_name(table)} DROP FOREIGN KEY {quote_name(constraint_name)}"
                )

            cursor.execute(
                """
                SELECT COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT
                FROM information_schema.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = %s
                  AND COLUMN_NAME = %s
                """,
                [table, old_column],
            )
            row = cursor.fetchone()
            if not row:
                return
            column_type, is_nullable, column_default = row

        null_sql = "NULL" if is_nullable == "YES" else "NOT NULL"
        default_sql = ""
        if column_default is not None:
            default_sql = f" DEFAULT {schema_editor.quote_value(column_default)}"

        schema_editor.execute(
            "ALTER TABLE {table} CHANGE COLUMN {old} {new} {col_type} {null_sql}{default_sql}".format(
                table=quote_name(table),
                old=quote_name(old_column),
                new=quote_name(expected_column),
                col_type=column_type,
                null_sql=null_sql,
                default_sql=default_sql,
            )
        )
    else:
        schema_editor.execute(
            f"ALTER TABLE {quote_name(table)} RENAME COLUMN {quote_name(old_column)} TO {quote_name(expected_column)}"
        )


def normalize_m2m_columns(apps, schema_editor):
    _rename_m2m_column(
        schema_editor,
        "aacampaign_campaign_constellations",
        _expected_m2m_column(apps, EVE_SDE_CONSTELLATION_MODEL),
    )
    _rename_m2m_column(
        schema_editor,
        "aacampaign_campaign_regions",
        _expected_m2m_column(apps, EVE_SDE_REGION_MODEL),
    )
    _rename_m2m_column(
        schema_editor,
        "aacampaign_campaign_systems",
        _expected_m2m_column(apps, EVE_SDE_SOLAR_SYSTEM_MODEL),
    )


class Migration(migrations.Migration):
    dependencies = [
        ("aacampaign", "0005_campaign_last_run"),
        migrations.swappable_dependency(EVE_SDE_REGION_MODEL),
        migrations.swappable_dependency(EVE_SDE_CONSTELLATION_MODEL),
        migrations.swappable_dependency(EVE_SDE_SOLAR_SYSTEM_MODEL),
    ]

    operations = [
        migrations.RunPython(normalize_m2m_columns, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="campaign",
            name="constellations",
            field=models.ManyToManyField(
                blank=True, related_name="campaigns", to=EVE_SDE_CONSTELLATION_MODEL
            ),
        ),
        migrations.AlterField(
            model_name="campaign",
            name="regions",
            field=models.ManyToManyField(
                blank=True, related_name="campaigns", to=EVE_SDE_REGION_MODEL
            ),
        ),
        migrations.AlterField(
            model_name="campaign",
            name="systems",
            field=models.ManyToManyField(
                blank=True, related_name="campaigns", to=EVE_SDE_SOLAR_SYSTEM_MODEL
            ),
        ),
        migrations.AlterField(
            model_name="campaignkillmail",
            name="solar_system",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                to=EVE_SDE_SOLAR_SYSTEM_MODEL,
            ),
        ),
    ]
