# Generated by Django 5.0.7 on 2024-07-26 19:23

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


def pre_migration(apps, schema_editor):
    Role = apps.get_model("nets_core", "Role")
    Permission = apps.get_model("nets_core", "Permission")

    ContentType = apps.get_model("contenttypes", "ContentType")
    unique_codenames = []
    for p in Permission.objects.all():
        if p.codename not in unique_codenames:
            unique_codenames.append(p.codename)
            other_permissions = Permission.objects.filter(codename=p.codename).exclude(
                id=p.id
            )
            if other_permissions.count() == 0:
                # update role permissions with the new permission
                for op in other_permissions:
                    for r in op.roles.all():
                        r.permissions.add(p)
                        r.permissions.remove(op)
                        r.save()
                # delete other permissions
                other_permissions.delete()
        else:
            p.delete()


def migrate_through(apps, schema_editor):
    Role = apps.get_model("nets_core", "Role")
    Permission = apps.get_model("nets_core", "Permission")
    RolePermission = apps.get_model("nets_core", "RolePermission")

    for role in Role.objects.all():
        for permission in role.permissions.all():
            RolePermission.objects.create(role=role, permission=permission)


class Migration(migrations.Migration):

    dependencies = [
        ("nets_core", "pre_migrate_role_permissions"),
    ]

    operations = [
        migrations.RemoveIndex(
            model_name="permission",
            name="permission_index",
        ),
        migrations.RemoveField(
            model_name="permission",
            name="project_content_type",
        ),
        migrations.RemoveField(
            model_name="permission",
            name="project_id",
        ),
        migrations.AlterField(
            model_name="permission",
            name="codename",
            field=models.CharField(
                max_length=150, unique=True, verbose_name="Codename"
            ),
        ),
        migrations.RemoveField(
            model_name="role",
            name="permissions",
        ),
        migrations.AddField(
            model_name="role",
            name="permissions",
            field=models.ManyToManyField(
                related_name="roles",
                through="nets_core.RolePermission",
                to="nets_core.permission",
            ),
        ),
    ]
