# Generated by Django 5.1.1 on 2024-11-13 05:14

from django.db import migrations
from django.db import models
from django.db import transaction
from django.utils.crypto import get_random_string


def migrate_customfield_selects(apps, schema_editor):
    """
    Migrate the custom field selects from a simple list of strings to a list of dictionaries with
    label and id. Then update all instances of the custom field to use the new format.
    """
    CustomFieldInstance = apps.get_model("documents", "CustomFieldInstance")
    CustomField = apps.get_model("documents", "CustomField")

    with transaction.atomic():
        for custom_field in CustomField.objects.filter(
            data_type="select",
        ):  # CustomField.FieldDataType.SELECT
            old_select_options = custom_field.extra_data["select_options"]
            custom_field.extra_data["select_options"] = [
                {"id": get_random_string(16), "label": value}
                for value in old_select_options
            ]
            custom_field.save()

            for instance in CustomFieldInstance.objects.filter(field=custom_field):
                if instance.value_select:
                    instance.value_select = custom_field.extra_data["select_options"][
                        int(instance.value_select)
                    ]["id"]
                    instance.save()


def reverse_migrate_customfield_selects(apps, schema_editor):
    """
    Reverse the migration of the custom field selects from a list of dictionaries with label and id
    to a simple list of strings. Then update all instances of the custom field to use the old format,
    which is just the index of the selected option.
    """
    CustomFieldInstance = apps.get_model("documents", "CustomFieldInstance")
    CustomField = apps.get_model("documents", "CustomField")

    with transaction.atomic():
        for custom_field in CustomField.objects.all():
            if custom_field.data_type == "select":  # CustomField.FieldDataType.SELECT
                old_select_options = custom_field.extra_data["select_options"]
                custom_field.extra_data["select_options"] = [
                    option["label"]
                    for option in custom_field.extra_data["select_options"]
                ]
                custom_field.save()

                for instance in CustomFieldInstance.objects.filter(field=custom_field):
                    instance.value_select = next(
                        index
                        for index, option in enumerate(old_select_options)
                        if option.get("id") == instance.value_select
                    )
                    instance.save()


class Migration(migrations.Migration):
    dependencies = [
        ("documents", "1059_workflowactionemail_workflowactionwebhook_and_more"),
    ]

    operations = [
        migrations.AlterField(
            model_name="customfieldinstance",
            name="value_select",
            field=models.CharField(max_length=16, null=True),
        ),
        migrations.RunPython(
            migrate_customfield_selects,
            reverse_migrate_customfield_selects,
        ),
    ]
