"""Remodel CharacterBlueprint.character from memberaudit onto corptools.

CharacterBlueprint is a rebuildable ESI mirror, so rows with no corptools
counterpart are deleted rather than kept. Both the old and new FK are named
``character`` (db column ``character_id``), so we route through a temporary
``character_audit`` FK: add it null=True, remap each row by matching the
corptools CharacterAudit whose EveCharacter equals the legacy memberaudit
Character's EveCharacter (deleting orphans), drop the old ``character`` FK, then
rename the temp field back to ``character`` and finalise it non-null.
"""

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


def remap(apps, schema_editor):
    CharacterBlueprint = apps.get_model("shop", "CharacterBlueprint")
    CharacterAudit = apps.get_model("corptools", "CharacterAudit")
    try:
        from memberaudit.models import Character
    except ImportError:
        # fresh install: no legacy memberaudit blueprints to remap. The mirror is
        # rebuilt from ESI on the next refresh, so any stray rows are dropped.
        CharacterBlueprint.objects.all().delete()
        return
    for src in CharacterBlueprint.objects.all():
        ma = (
            Character.objects.filter(pk=src.character_id)
            .select_related("eve_character")
            .first()
        )
        # Match by the EVE character id (an int) rather than passing the
        # memberaudit EveCharacter instance: historical models live in a
        # separate app registry and reject cross-registry instances.
        audit = (
            CharacterAudit.objects.filter(
                character__character_id=ma.eve_character.character_id
            ).first()
            if ma
            else None
        )
        if audit is None:
            src.delete()  # rebuildable mirror: drop rows with no corptools owner
            continue
        src.character_audit_id = audit.pk
        src.save(update_fields=["character_audit"])


def noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("shop", "0021_shopsource_corptools"),
        ("corptools", "__first__"),
    ]

    operations = [
        migrations.AddField(
            model_name="characterblueprint",
            name="character_audit",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="+",
                to="corptools.characteraudit",
            ),
        ),
        migrations.RunPython(remap, noop),
        migrations.RemoveField(
            model_name="characterblueprint",
            name="character",
        ),
        migrations.RenameField(
            model_name="characterblueprint",
            old_name="character_audit",
            new_name="character",
        ),
        migrations.AlterField(
            model_name="characterblueprint",
            name="character",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="+",
                to="corptools.characteraudit",
            ),
        ),
    ]
