# Generated by Django 3.2.13 on 2023-01-05 10:09

from django.db import migrations


def forward(apps, schema_editor):
    Role = apps.get_model("baserow_enterprise", "Role")
    RoleAssignment = apps.get_model("baserow_enterprise", "RoleAssignment")
    GroupUser = apps.get_model("core", "GroupUser")

    # If we have a `NO_ROLE` role, then we have some work to do.
    if Role.objects.filter(uid="NO_ROLE").exists():
        # If there is no `NO_ACCESS` role, then we
        # can safely rename `NO_ROLE` to `NO_ACCESS`.
        if not Role.objects.filter(uid="NO_ACCESS").exists():
            Role.objects.filter(uid="NO_ROLE").update(uid="NO_ACCESS")
        else:
            # Things become more complicated if we have
            # both `NO_ROLE` and `NO_ACCESS` roles.
            no_role = Role.objects.get(uid="NO_ROLE")
            no_access = Role.objects.get(uid="NO_ACCESS")

            # Do we have any `RoleAssignment` pointing to `NO_ROLE`?
            if not RoleAssignment.objects.filter(role=no_role).exists():
                # There aren't any - we can safely delete `NO_ROLE`.
                no_role.delete()
            # Do we have any `RoleAssignment` pointing to `NO_ACCESS`?
            elif not RoleAssignment.objects.filter(role=no_access).exists():
                # There aren't any - we'll delete `NO_ACCESS` and
                # instead rename `NO_ROLE` to `NO_ACCESS`.
                no_access.delete()
                Role.objects.filter(uid="NO_ROLE").update(uid="NO_ACCESS")
            else:
                # We have assignment for both no_role and no_access. It shouldn't
                # happen but we never know. In this scenario we have to find the
                # RoleAssignment pointing to NO_ROLE and change them to NO_ACCESS,
                # then delete the NO_ROLE role.
                RoleAssignment.objects.filter(role=no_role).update(role=no_access)
                no_role.delete()

    GroupUser.objects.filter(permissions="NO_ROLE").update(permissions="NO_ACCESS")


class Migration(migrations.Migration):
    dependencies = [
        ("baserow_enterprise", "0009_roleassignment_subject_and_scope_uniqueness"),
    ]
    run_before = [("core", "0046_rename_group_workspace")]

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