# Generated by Discord Obfuscate on 2026-02-20

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


def backfill_obfuscation(apps, schema_editor):
    Assignment = apps.get_model("discord_obfuscate", "DiscordRoleColorAssignment")
    Obfuscation = apps.get_model("discord_obfuscate", "DiscordRoleObfuscation")

    role_to_config = {
        row["role_id"]: row["id"]
        for row in Obfuscation.objects.exclude(role_id=None).values("id", "role_id")
    }
    if not role_to_config:
        return

    for assignment in Assignment.objects.filter(role_id__in=role_to_config.keys()):
        assignment.obfuscation_id = role_to_config.get(assignment.role_id)
        assignment.save(update_fields=["obfuscation"])


def clear_obfuscation(apps, schema_editor):
    Assignment = apps.get_model("discord_obfuscate", "DiscordRoleColorAssignment")
    Assignment.objects.update(obfuscation=None)


class Migration(migrations.Migration):
    dependencies = [
        ("discord_obfuscate", "0003_random_key_reposition_min_position"),
    ]

    operations = [
        migrations.AddField(
            model_name="discordrolecolorassignment",
            name="obfuscation",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="color_assignments",
                to="discord_obfuscate.discordroleobfuscation",
            ),
        ),
        migrations.RunPython(backfill_obfuscation, clear_obfuscation),
    ]
