# Generated by Django 5.2.1 on 2025-06-10 03:04

from django.db import migrations, models


def migrate_collection_relationships(apps, schema_editor):
    """
    Migrate existing ForeignKey relationships to ManyToMany relationships
    """
    Adventure = apps.get_model('adventures', 'Adventure')
    
    # Get all adventures that have a collection assigned
    adventures_with_collections = Adventure.objects.filter(collection__isnull=False)
    
    for adventure in adventures_with_collections:
        # Add the existing collection to the new many-to-many field
        adventure.collections.add(adventure.collection_id)


def reverse_migrate_collection_relationships(apps, schema_editor):
    """
    Reverse migration - convert first collection back to ForeignKey
    Note: This will only preserve the first collection if an adventure has multiple
    """
    Adventure = apps.get_model('adventures', 'Adventure')
    
    for adventure in Adventure.objects.all():
        first_collection = adventure.collections.first()
        if first_collection:
            adventure.collection = first_collection
            adventure.save()


class Migration(migrations.Migration):

    dependencies = [
        ('adventures', '0034_remove_adventureimage_unique_immich_id_per_user'),
    ]

    operations = [
        # First, add the new ManyToMany field
        migrations.AddField(
            model_name='adventure',
            name='collections',
            field=models.ManyToManyField(blank=True, related_name='adventures', to='adventures.collection'),
        ),
        
        # Migrate existing data from old field to new field
        migrations.RunPython(
            migrate_collection_relationships,
            reverse_migrate_collection_relationships
        ),
        
        # Finally, remove the old ForeignKey field
        migrations.RemoveField(
            model_name='adventure',
            name='collection',
        ),
    ]