# Generated by Django 5.2.4 on 2025-09-22 01:00

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


def set_manager_node_for_existing(apps, schema_editor):
    NodeModel = apps.get_model("nodes", "Node")
    Charger = apps.get_model("ocpp", "Charger")
    db_alias = schema_editor.connection.alias

    runtime_node_cls = None
    try:
        from nodes.models import Node as RuntimeNode

        runtime_node_cls = RuntimeNode
    except Exception:
        runtime_node_cls = None

    local_node = None
    if runtime_node_cls is not None:
        try:
            local_node = runtime_node_cls.get_local()
        except Exception:
            local_node = None

    if not local_node and runtime_node_cls is not None:
        try:
            mac_address = runtime_node_cls.get_current_mac()
        except Exception:
            mac_address = None
        if mac_address:
            local_node = (
                NodeModel.objects.using(db_alias)
                .filter(mac_address=mac_address)
                .first()
            )

    if not local_node:
        return

    Charger.objects.using(db_alias).filter(
        manager_node__isnull=True
    ).update(manager_node=local_node.pk)


class Migration(migrations.Migration):

    dependencies = [
        ("nodes", "0006_emailoutbox_group_emailoutbox_user"),
        ("ocpp", "0016_simulator_door_open"),
    ]

    operations = [
        migrations.AddField(
            model_name="charger",
            name="manager_node",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="managed_chargers",
                to="nodes.node",
            ),
        ),
        migrations.RunPython(set_manager_node_for_existing, migrations.RunPython.noop),
    ]
