# Generated by Django 4.1.5 on 2023-01-23 19:42
from uuid import uuid4

from django.apps.registry import Apps
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor


def set_generated_name(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    db_alias = schema_editor.connection.alias
    Prompt = apps.get_model("authentik_stages_prompt", "prompt")

    for prompt in Prompt.objects.using(db_alias).all():
        name = prompt.field_key
        stage = prompt.promptstage_set.order_by("name").first()
        if stage:
            name += "_" + stage.name
        else:
            name += "_" + str(uuid4())
        prompt.name = name
        prompt.save()


class Migration(migrations.Migration):
    dependencies = [
        ("authentik_stages_prompt", "0008_alter_prompt_type"),
    ]

    operations = [
        migrations.AddField(
            model_name="prompt",
            name="name",
            field=models.TextField(default="", unique=False, db_index=False, blank=False),
            preserve_default=False,
        ),
        migrations.RunPython(code=set_generated_name),
        migrations.AlterField(
            model_name="prompt",
            name="name",
            field=models.TextField(unique=True),
        ),
    ]
