# Generated by Django 3.2.18 on 2024-01-25 10:51

from django.db import migrations


def update_admin_roles_permissions(apps, schema_editor):
    Operation = apps.get_model('a2_rbac', 'Operation')
    try:
        view_operation = Operation.objects.get(slug='view')
    except Operation.DoesNotExist:
        return

    OrganizationalUnit = apps.get_model('a2_rbac', 'OrganizationalUnit')
    Permission = apps.get_model('a2_rbac', 'Permission')
    User = apps.get_model('custom_user', 'User')
    ContentType = apps.get_model('contenttypes', 'ContentType')

    target_ct = ContentType.objects.get_for_model(ContentType)
    target_id = ContentType.objects.get_for_model(User).pk
    user_view_permission_qs = Permission.objects.filter(
        operation=view_operation, target_ct=target_ct, target_id=target_id
    )
    global_user_view_permission = user_view_permission_qs.get(ou__isnull=True)
    for ou in OrganizationalUnit.objects.exclude(default=True):
        try:
            ou_user_view_permission = user_view_permission_qs.get(ou=ou)
        except Permission.DoesNotExist:
            continue
        # admin roles start with _
        for r in ou.role_set.filter(slug__startswith='_'):
            if ou_user_view_permission not in r.permissions.all():
                continue
            r.permissions.remove(global_user_view_permission)
            r.permissions.add(ou_user_view_permission)


class Migration(migrations.Migration):
    dependencies = [
        ('a2_rbac', '0038_organizationalunit_phone_is_unique'),
    ]

    operations = [
        migrations.RunPython(update_admin_roles_permissions, reverse_code=migrations.RunPython.noop)
    ]
