# Generated by Django 5.1.6 on 2025-03-06 08:13
import time

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

BATCH_SIZE = 10000
RECIPIENT_PERSONAL = 1
RECIPIENT_HUDDLE = 3


def update_dm_and_gdm_topic_name(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    Message = apps.get_model("zerver", "Message")

    if not Message.objects.exists():
        # Nothing to do, and Message.objects.latest() will crash.
        return

    last_id = Message.objects.latest("id").id

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

    try:
        third_party_import_client = Client.objects.get(name="populate_db")
    except (Client.DoesNotExist, Client.MultipleObjectsReturned):
        return

    def process_batch(id_start: int, id_end: int) -> None:
        messages_to_update = Message.objects.filter(
            id__gte=id_start,
            id__lte=id_end,
            sending_client_id=third_party_import_client.id,
            recipient__type__in=[RECIPIENT_PERSONAL, RECIPIENT_HUDDLE],
        ).exclude(subject="")

        messages_to_update.update(subject="")

    id_range_lower_bound = 0
    id_range_upper_bound = min(BATCH_SIZE, last_id)

    while id_range_lower_bound < last_id:
        process_batch(id_range_lower_bound, id_range_upper_bound)
        print(f"Processed messages up to ID {id_range_upper_bound} / {last_id}")

        id_range_lower_bound = id_range_upper_bound
        id_range_upper_bound = min(id_range_lower_bound + BATCH_SIZE, last_id)

        time.sleep(0.1)


class Migration(migrations.Migration):
    atomic = False
    dependencies = [
        ("zerver", "0696_rename_no_topic_to_empty_string_topic"),
    ]

    operations = [
        migrations.RunPython(update_dm_and_gdm_topic_name),
    ]
