# Generated by Django 5.2.7 on 2025-11-06 04:47

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


def forwards(apps, schema_editor):
    Configuration = apps.get_model("ocpp", "ChargerConfiguration")
    ConfigurationKey = apps.get_model("ocpp", "ConfigurationKey")

    for configuration in Configuration.objects.all():
        entries = getattr(configuration, "configuration_keys", None) or []
        objects = []
        for index, entry in enumerate(entries):
            if not isinstance(entry, dict):
                continue
            key_text = str(entry.get("key") or "").strip()
            if not key_text:
                continue
            readonly = bool(entry.get("readonly"))
            has_value = "value" in entry
            value = entry.get("value") if has_value else None
            extras = {
                field_key: field_value
                for field_key, field_value in entry.items()
                if field_key not in {"key", "readonly", "value"}
            }
            objects.append(
                ConfigurationKey(
                    configuration=configuration,
                    position=index,
                    key=key_text,
                    readonly=readonly,
                    has_value=has_value,
                    value=value,
                    extra_data=extras,
                )
            )
        if objects:
            ConfigurationKey.objects.bulk_create(objects)


def backwards(apps, schema_editor):
    Configuration = apps.get_model("ocpp", "ChargerConfiguration")
    ConfigurationKey = apps.get_model("ocpp", "ConfigurationKey")

    for configuration in Configuration.objects.all():
        payload = []
        for entry in ConfigurationKey.objects.filter(
            configuration=configuration
        ).order_by("position", "id"):
            data = {"key": entry.key, "readonly": entry.readonly}
            if entry.has_value:
                data["value"] = entry.value
            if entry.extra_data:
                data.update(entry.extra_data)
            payload.append(data)
        configuration.configuration_keys = payload
        configuration.save(update_fields=["configuration_keys"])


class Migration(migrations.Migration):

    dependencies = [
        ("ocpp", "0039_merge_20251105_1842"),
    ]

    operations = [
        migrations.CreateModel(
            name="ConfigurationKey",
            fields=[
                (
                    "id",
                    models.BigAutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("position", models.PositiveIntegerField(default=0)),
                ("key", models.CharField(max_length=255)),
                ("readonly", models.BooleanField(default=False)),
                ("has_value", models.BooleanField(default=False)),
                ("value", models.JSONField(blank=True, null=True)),
                ("extra_data", models.JSONField(blank=True, default=dict)),
                (
                    "configuration",
                    models.ForeignKey(
                        on_delete=django.db.models.deletion.CASCADE,
                        related_name="configuration_entries",
                        to="ocpp.chargerconfiguration",
                    ),
                ),
            ],
            options={
                "verbose_name": "Configuration Key",
                "verbose_name_plural": "Configuration Keys",
                "ordering": ["position", "id"],
            },
        ),
        migrations.RunPython(forwards, backwards),
        migrations.RemoveField(
            model_name="chargerconfiguration",
            name="configuration_keys",
        ),
    ]
