from django.db import migrations, models

import servala.core.validators


def populate_display_name(apps, schema_editor):
    """
    For existing instances, copy name to display_name.
    Existing instances already have their name matching the k8s resource,
    so we cannot add a prefix.
    """
    ServiceInstance = apps.get_model("core", "ServiceInstance")
    for instance in ServiceInstance.objects.all():
        instance.display_name = instance.name
        instance.save(update_fields=["display_name"])


class Migration(migrations.Migration):
    dependencies = [
        ("core", "0018_add_invoice_grouping_to_organization_origin"),
    ]

    operations = [
        migrations.AlterField(
            model_name="serviceinstance",
            name="name",
            field=models.CharField(
                max_length=63,
                validators=[servala.core.validators.kubernetes_name_validator],
                verbose_name="Instance ID",
            ),
        ),
        # Add display_name field with a temporary default
        migrations.AddField(
            model_name="serviceinstance",
            name="display_name",
            field=models.CharField(
                default="",
                help_text="Display name for this instance",
                max_length=100,
                verbose_name="Name",
            ),
            preserve_default=False,
        ),
        migrations.RunPython(populate_display_name, migrations.RunPython.noop),
    ]
