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

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


def populate_ride_model_slugs(apps, schema_editor):
    """Populate unique slugs for existing RideModel records."""
    RideModel = apps.get_model("rides", "RideModel")
    apps.get_model("rides", "Company")

    for ride_model in RideModel.objects.all():
        # Generate base slug from manufacturer name + model name
        if ride_model.manufacturer:
            base_slug = slugify(f"{ride_model.manufacturer.name} {ride_model.name}")
        else:
            base_slug = slugify(ride_model.name)

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

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


def reverse_populate_ride_model_slugs(apps, schema_editor):
    """Reverse operation - clear slugs (not really needed but for completeness)."""
    RideModel = apps.get_model("rides", "RideModel")
    RideModel.objects.all().update(slug="")


class Migration(migrations.Migration):

    dependencies = [
        ("rides", "0010_add_comprehensive_ride_model_system"),
    ]

    operations = [
        migrations.RunPython(
            populate_ride_model_slugs,
            reverse_populate_ride_model_slugs,
        ),
    ]
