# Generated by Django 3.1.8 on 2021-04-20 10:09

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


def backfill_realm_creation_log_events(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    RealmAuditLog = apps.get_model("zerver", "RealmAuditLog")
    RealmAuditLog.REALM_CREATED = 215

    Realm = apps.get_model("zerver", "Realm")

    objects_to_create = []
    for realm in Realm.objects.all():
        entry = RealmAuditLog(
            realm=realm,
            event_type=RealmAuditLog.REALM_CREATED,
            event_time=realm.date_created,
            backfilled=True,
        )
        objects_to_create.append(entry)
    RealmAuditLog.objects.bulk_create(objects_to_create)


def reverse_code(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    RealmAuditLog = apps.get_model("zerver", "RealmAuditLog")
    RealmAuditLog.REALM_CREATED = 215
    RealmAuditLog.objects.filter(event_type=RealmAuditLog.REALM_CREATED, backfilled=True).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("zerver", "0321_userprofile_enable_marketing_emails"),
    ]

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