# Generated by Django 4.2.1 on 2023-06-03 10:53

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


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

    UserGroup.ADMINISTRATORS_GROUP_NAME = "role:administrators"

    for realm in Realm.objects.all().iterator():
        if realm.create_multiuse_invite_group is not None:
            continue

        # Prior to the new create_multiuse_invite_group field being
        # created, multi-use invitation links could only be created
        # and managed by administrators, regardless of
        # invite_to_realm_policy. We replicate that policy for the
        # initial value of the new setting.
        admins_group = UserGroup.objects.get(
            name=UserGroup.ADMINISTRATORS_GROUP_NAME, realm=realm, is_system_group=True
        )
        realm.create_multiuse_invite_group = admins_group

        realm.save(update_fields=["create_multiuse_invite_group"])


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("zerver", "0469_realm_create_multiuse_invite_group"),
    ]

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