# Generated by Django 5.2.7 on 2025-03-01 00:00

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


def migrate_location_permissions(apps, schema_editor):
    ContentType = apps.get_model("contenttypes", "ContentType")
    Permission = apps.get_model("auth", "Permission")
    Group = apps.get_model("auth", "Group")

    user_app_label, user_model_name = settings.AUTH_USER_MODEL.split(".")
    UserModel = apps.get_model(user_app_label, user_model_name)
    GroupPermission = Group.permissions.through
    UserPermission = UserModel.user_permissions.through

    db_alias = schema_editor.connection.alias

    try:
        ocpp_ct = ContentType.objects.using(db_alias).get(
            app_label="ocpp", model="location"
        )
    except ContentType.DoesNotExist:
        return

    core_ct, _ = ContentType.objects.using(db_alias).get_or_create(
        app_label="core", model="location"
    )

    ocpp_perms = list(
        Permission.objects.using(db_alias).filter(content_type=ocpp_ct)
    )
    ocpp_by_codename = {perm.codename: perm for perm in ocpp_perms}

    duplicates = Permission.objects.using(db_alias).filter(
        content_type=core_ct, codename__in=ocpp_by_codename.keys()
    )

    for duplicate in duplicates:
        target = ocpp_by_codename.get(duplicate.codename)
        if target is None:
            continue

        GroupPermission.objects.using(db_alias).filter(
            permission_id=duplicate.pk
        ).update(permission_id=target.pk)

        UserPermission.objects.using(db_alias).filter(
            permission_id=duplicate.pk
        ).update(permission_id=target.pk)

        duplicate.delete(using=db_alias)

    for permission in ocpp_perms:
        permission.content_type = core_ct
        permission.save(update_fields=["content_type"])

    ContentType.objects.using(db_alias).filter(pk=ocpp_ct.pk).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("ocpp", "0047_location_table_to_core"),
        ("core", "0098_location_model"),
        ("teams", "0018_manualtask_location_to_core"),
    ]

    operations = [
        migrations.AlterField(
            model_name="charger",
            name="location",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="chargers",
                to="core.location",
            ),
        ),
        migrations.AlterField(
            model_name="cpreservation",
            name="location",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.PROTECT,
                related_name="reservations",
                to="core.location",
                verbose_name="Location",
            ),
        ),
        migrations.RunPython(
            migrate_location_permissions,
            reverse_code=migrations.RunPython.noop,
        ),
        migrations.SeparateDatabaseAndState(
            database_operations=[],
            state_operations=[migrations.DeleteModel(name="Location")],
        ),
    ]
