# Generated by Django 3.2.18 on 2023-06-08 14:31

from django.db import migrations


def ensure_unique_object_permission_names(apps, schema_editor):
    ObjectPermission = apps.get_model("users", "ObjectPermission")

    cache = set()
    for instance in ObjectPermission.objects.all():
        name = instance.name
        counter = 1
        while name in cache:
            suffix = f" {counter}"
            max_name_length = 100 - len(suffix)
            name = f"{instance.name[:max_name_length]}{suffix}"
            counter += 1

        if name != instance.name:
            print(f'    Object Permission instance {instance.id} is being renamed to "{name}" for uniqueness')
            instance.name = name
            instance.save()

        cache.add(name)


class Migration(migrations.Migration):
    dependencies = [
        ("users", "0004_alter_user_managers"),
    ]

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