"""Phase 2 — Backfill idswh on all existing GuestStay rows.

Uses uuid.uuid4().hex directly (not the model's save() method) so the
migration is self-contained and does not depend on application code that
may change in the future.

Processes rows in batches of 500 to avoid long-running transactions on
large tables.

Reverse: noop — idswh values are permanent; rolling back the migration
would drop the column anyway (handled by 0010's reverse).
"""
from __future__ import annotations

import uuid

from django.db import migrations


_BATCH_SIZE = 500


def backfill_idswh(apps, schema_editor):
    GuestStay = apps.get_model("guests", "GuestStay")

    # Collect PKs of rows that need backfilling.
    pks = list(
        GuestStay.objects.filter(idswh__isnull=True).values_list("pk", flat=True)
    )

    # Process in batches to keep individual UPDATE statements small.
    for batch_start in range(0, len(pks), _BATCH_SIZE):
        batch_pks = pks[batch_start : batch_start + _BATCH_SIZE]
        stays = GuestStay.objects.filter(pk__in=batch_pks)
        for stay in stays:
            stay.idswh = uuid.uuid4().hex
        GuestStay.objects.bulk_update(stays, ["idswh"])


class Migration(migrations.Migration):

    dependencies = [
        ("guests", "0010_gueststay"),
    ]

    operations = [
        migrations.RunPython(backfill_idswh, reverse_code=migrations.RunPython.noop),
    ]
