"""
catalog_app/migrations/0042_backfill_book_slugs.py
One-off backfill for Book.slug, added in 0041, on every book that already
existed before slugs were introduced. New books get a slug automatically via
Book.save() going forward — this migration only covers the pre-existing rows,
which all have slug=NULL right after 0041 runs.
"""

from django.db import migrations
from django.utils.text import slugify


def backfill(apps, schema_editor):
    Book = apps.get_model("catalog_app", "Book")

    existing_slugs = set(
        Book.objects.exclude(slug__isnull=True).exclude(slug="").values_list("slug", flat=True)
    )

    for book in Book.objects.filter(slug__isnull=True).only("id", "title"):
        base = slugify(book.title)[:290] or "book"
        slug = base
        suffix = 2
        while slug in existing_slugs:
            slug = f"{base}-{suffix}"
            suffix += 1
        existing_slugs.add(slug)
        book.slug = slug
        book.save(update_fields=["slug"])


def unbackfill(apps, schema_editor):
    pass  # non-destructive reverse — leaves backfilled slugs in place


class Migration(migrations.Migration):
    dependencies = [
        ("catalog_app", "0041_book_slug"),
    ]

    operations = [
        migrations.RunPython(backfill, unbackfill),
    ]
