# Generated by Django 4.2.8 on 2024-01-01 10:03


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_default_value_for_direct_message_initiator_group_and_more(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    Realm = apps.get_model("zerver", "Realm")
    NamedUserGroup = apps.get_model("zerver", "NamedUserGroup")

    EVERYONE_GROUP_NAME = "role:everyone"
    NOBODY_GROUP_NAME = "role:nobody"
    PRIVATE_MESSAGE_POLICY_DISABLED = 2

    Realm.objects.filter(
        direct_message_initiator_group=None,
    ).update(
        direct_message_initiator_group=NamedUserGroup.objects.filter(
            name=EVERYONE_GROUP_NAME, realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )
    Realm.objects.filter(
        direct_message_permission_group=None, private_message_policy=PRIVATE_MESSAGE_POLICY_DISABLED
    ).update(
        direct_message_permission_group=NamedUserGroup.objects.filter(
            name=NOBODY_GROUP_NAME, realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )
    Realm.objects.filter(
        direct_message_permission_group=None,
    ).exclude(private_message_policy=PRIVATE_MESSAGE_POLICY_DISABLED).update(
        direct_message_permission_group=NamedUserGroup.objects.filter(
            name=EVERYONE_GROUP_NAME, realm=OuterRef("id"), is_system_group=True
        ).values("pk")
    )


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("zerver", "0549_realm_direct_message_initiator_group_and_more"),
    ]

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