from uuid import uuid4

from django.db import migrations


def backfill_share_token(apps, schema_editor):
    Scrobble = apps.get_model("scrobbles", "Scrobble")
    batch = []
    for scrobble in Scrobble.objects.filter(share_token__isnull=True).iterator(
        chunk_size=500
    ):
        scrobble.share_token = uuid4()
        batch.append(scrobble)
    if batch:
        Scrobble.objects.bulk_update(batch, ["share_token"], batch_size=500)


class Migration(migrations.Migration):

    dependencies = [
        ("scrobbles", "0091_scrobble_share_token_scrobble_visibility"),
    ]

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