# Generated by Django 5.2.5 on 2025-08-28 19:19

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


def update_ride_model_slugs(apps, schema_editor):
    """Update RideModel slugs to be just the model name, not manufacturer + name."""
    RideModel = apps.get_model("rides", "RideModel")

    for ride_model in RideModel.objects.all():
        # Generate new slug from just the name
        new_slug = slugify(ride_model.name)

        # Ensure uniqueness within the same manufacturer
        counter = 1
        base_slug = new_slug
        while (
            RideModel.objects.filter(manufacturer=ride_model.manufacturer, slug=new_slug)
            .exclude(pk=ride_model.pk)
            .exists()
        ):
            new_slug = f"{base_slug}-{counter}"
            counter += 1

        # Update the slug
        ride_model.slug = new_slug
        ride_model.save(update_fields=["slug"])
        print(f"Updated {ride_model.name}: {ride_model.slug}")


def reverse_ride_model_slugs(apps, schema_editor):
    """Reverse the slug update by regenerating the old format."""
    RideModel = apps.get_model("rides", "RideModel")

    for ride_model in RideModel.objects.all():
        # Generate old-style slug with manufacturer + name
        old_slug = slugify(f"{ride_model.manufacturer.name if ride_model.manufacturer else ''} {ride_model.name}")

        # Ensure uniqueness globally (old way)
        counter = 1
        base_slug = old_slug
        while RideModel.objects.filter(slug=old_slug).exclude(pk=ride_model.pk).exists():
            old_slug = f"{base_slug}-{counter}"
            counter += 1

        # Update the slug
        ride_model.slug = old_slug
        ride_model.save(update_fields=["slug"])


class Migration(migrations.Migration):

    dependencies = [
        ("rides", "0013_fix_ride_model_slugs"),
    ]

    operations = [
        migrations.RunPython(
            update_ride_model_slugs,
            reverse_ride_model_slugs,
        ),
    ]
