# Generated by Django 5.0.8 on 2024-09-05 06:11

from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models import OuterRef


def set_can_manage_all_groups_for_existing_realms(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Realm = apps.get_model("zerver", "Realm")
    NamedUserGroup = apps.get_model("zerver", "NamedUserGroup")

    MEMBERS_ONLY = 1
    ADMINS_ONLY = 2
    FULL_MEMBERS_ONLY = 3
    MODERATORS_ONLY = 4

    Realm.objects.filter(can_manage_all_groups=None, user_group_edit_policy=MEMBERS_ONLY).update(
        can_manage_all_groups=NamedUserGroup.objects.filter(
            name="role:members", realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )
    Realm.objects.filter(can_manage_all_groups=None, user_group_edit_policy=ADMINS_ONLY).update(
        can_manage_all_groups=NamedUserGroup.objects.filter(
            name="role:administrators", realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )
    Realm.objects.filter(
        can_manage_all_groups=None, user_group_edit_policy=FULL_MEMBERS_ONLY
    ).update(
        can_manage_all_groups=NamedUserGroup.objects.filter(
            name="role:fullmembers", realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )
    Realm.objects.filter(can_manage_all_groups=None, user_group_edit_policy=MODERATORS_ONLY).update(
        can_manage_all_groups=NamedUserGroup.objects.filter(
            name="role:moderators", realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )


class Migration(migrations.Migration):
    dependencies = [
        ("zerver", "0591_realm_add_can_manage_all_groups"),
    ]

    operations = [
        migrations.RunPython(
            set_can_manage_all_groups_for_existing_realms,
            elidable=True,
            reverse_code=migrations.RunPython.noop,
        )
    ]
