# Generated by Django 4.1.7 on 2023-03-27 03:00

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


def create_nobody_system_user_group_for_existing_realms(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Realm = apps.get_model("zerver", "Realm")
    UserGroup = apps.get_model("zerver", "UserGroup")
    NOBODY_GROUP_NAME = "@role:nobody"
    NOBODY_GROUP_DESCRIPTION = "Nobody"

    groups_to_create = [
        UserGroup(
            name=NOBODY_GROUP_NAME,
            description=NOBODY_GROUP_DESCRIPTION,
            realm=realm,
            is_system_group=True,
        )
        for realm in Realm.objects.all()
    ]

    UserGroup.objects.bulk_create(groups_to_create)


def delete_nobody_system_user_groups(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    UserGroup = apps.get_model("zerver", "UserGroup")
    NOBODY_GROUP_NAME = "@role:nobody"

    UserGroup.objects.filter(name=NOBODY_GROUP_NAME, is_system_group=True).delete()


class Migration(migrations.Migration):
    dependencies = [
        ("zerver", "0433_preregistrationrealm"),
    ]

    operations = [
        migrations.RunPython(
            create_nobody_system_user_group_for_existing_realms,
            reverse_code=delete_nobody_system_user_groups,
            elidable=True,
        ),
    ]
