# Generated by Django 5.2.4 on 2025-09-17 02:18

from django.db import migrations


def assign_locations(apps, schema_editor):
    Location = apps.get_model("ocpp", "Location")
    Charger = apps.get_model("ocpp", "Charger")

    db_alias = schema_editor.connection.alias

    for charger in Charger.objects.using(db_alias).filter(location__isnull=True):
        existing_location_id = (
            Charger.objects.using(db_alias)
            .filter(charger_id=charger.charger_id, location__isnull=False)
            .exclude(pk=charger.pk)
            .values_list("location_id", flat=True)
            .first()
        )
        if existing_location_id:
            location = (
                Location.objects.using(db_alias).filter(pk=existing_location_id).first()
            )
        else:
            location, _ = Location.objects.using(db_alias).get_or_create(
                name=charger.charger_id
            )
        if location:
            charger.location = location
            charger.save(update_fields=["location"])


def noop(apps, schema_editor):
    """Reverse operation placeholder."""


class Migration(migrations.Migration):

    dependencies = [
        ("ocpp", "0005_brand_evmodel"),
    ]

    operations = [
        migrations.RunPython(assign_locations, noop),
    ]
