# Generated by Django 5.2.4 on 2025-08-05 08:53

from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models.functions import Lower


def migrate_set_order_value(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    Realm = apps.get_model("zerver", "Realm")
    ChannelFolder = apps.get_model("zerver", "ChannelFolder")

    realms = Realm.objects.all()

    for realm in realms:
        channel_folders = list(
            ChannelFolder.objects.filter(realm_id=realm.id)
            .annotate(lower_name=Lower("name"))
            .order_by("lower_name")
        )

        for index, folder in enumerate(channel_folders):
            folder.order = index

        ChannelFolder.objects.bulk_update(channel_folders, ["order"])


class Migration(migrations.Migration):
    dependencies = [
        ("zerver", "0747_realmcreationstatus"),
    ]

    operations = [
        migrations.AddField(
            model_name="channelfolder",
            name="order",
            field=models.IntegerField(default=0),
        ),
        migrations.RunPython(
            migrate_set_order_value, reverse_code=migrations.RunPython.noop, elidable=True
        ),
    ]
