# Generated by Django 5.2.7 on 2025-11-21 13:51

from django.db import migrations, models, transaction
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models import Max, Min


def migrate_existing_zoom_tokens(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    BATCH_SIZE = 10000
    UserProfile = apps.get_model("zerver", "UserProfile")

    applicable_user_rows = UserProfile.objects.filter(zoom_token__isnull=False)
    max_id = applicable_user_rows.aggregate(Max("id"))["id__max"]
    lower_bound = applicable_user_rows.aggregate(Min("id"))["id__min"]

    if max_id is None or lower_bound is None:
        # no users to migrate
        return

    while lower_bound <= max_id:
        upper_bound = lower_bound + BATCH_SIZE - 1
        print(f"Processing batch {lower_bound} to {upper_bound} for Zoom token migration")
        with transaction.atomic():
            users = applicable_user_rows.filter(id__gte=lower_bound, id__lte=upper_bound)
            for user in users.iterator():
                user.third_party_api_state["zoom"] = user.zoom_token
                user.save(update_fields=["third_party_api_state"])
        lower_bound = upper_bound + 1


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

    operations = [
        migrations.AddField(
            model_name="userprofile",
            name="third_party_api_state",
            field=models.JSONField(default=dict, db_default={}),
        ),
        migrations.RunPython(migrate_existing_zoom_tokens, reverse_code=migrations.RunPython.noop),
        migrations.RemoveField(
            model_name="userprofile",
            name="zoom_token",
        ),
    ]
