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

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


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

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

    for author in Author.objects.filter(slug__isnull=True).only("id", "name"):
        base = slugify(author.name)[:290] or "author"
        slug = base
        suffix = 2
        while slug in existing_slugs:
            slug = f"{base}-{suffix}"
            suffix += 1
        existing_slugs.add(slug)
        author.slug = slug
        author.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", "0043_author_slug"),
    ]

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