"""Drop the legacy `billboard-` slug prefix from billboard applets and
rename Most Recent → Most Recent Scroll.

The `billboard-` prefix snuck into seed migration 0003 against intent — no
other context (dashboard, gameboard, wallet, game-kit) prefixes its applet
slugs with the context name, and slugs need to stay portable so users can
later rearrange which page hosts which applet.
"""
from django.db import migrations


RENAMES = [
    # (old_slug,                new_slug,             new_name_or_None)
    ('billboard-my-scrolls',    'my-scrolls',         None),
    ('billboard-my-contacts',   'my-contacts',        None),
    ('billboard-most-recent',   'most-recent-scroll', 'Most Recent Scroll'),
    ('billboard-notes',         'notes',              None),
]


def _apply(apps, mapping):
    Applet = apps.get_model('applets', 'Applet')
    for old_slug, new_slug, new_name in mapping:
        try:
            applet = Applet.objects.get(slug=old_slug)
        except Applet.DoesNotExist:
            continue
        applet.slug = new_slug
        fields = ['slug']
        if new_name is not None:
            applet.name = new_name
            fields.append('name')
        applet.save(update_fields=fields)


def forward(apps, schema_editor):
    _apply(apps, RENAMES)


def backward(apps, schema_editor):
    inverse = [
        (new, old, 'Most Recent' if old == 'billboard-most-recent' else None)
        for (old, new, _) in RENAMES
    ]
    _apply(apps, inverse)


class Migration(migrations.Migration):

    dependencies = [
        ('applets', '0003_seed_applets'),
    ]

    operations = [
        migrations.RunPython(forward, backward),
    ]
