# Generated by Django 5.2.6 on 2026-01-04 21:45

from django.db import migrations


def populate_path_and_depth(apps, schema_editor):
    """Populate path and depth fields for all existing events."""
    Event = apps.get_model('eventhub', 'Event')
    
    def update_event_path(event, parent_path='', parent_depth=-1):
        """Recursively update path and depth for an event and its children."""
        if parent_path:
            event.path = f"{parent_path}{event.id}/"
            event.depth = parent_depth + 1
        else:
            # Root event (no parent)
            event.path = "/"
            event.depth = 0
        
        # Save the event (avoid triggering save() override by using update)
        Event.objects.filter(pk=event.pk).update(path=event.path, depth=event.depth)
        
        # Update all children
        current_path = f"{event.path}{event.id}/"
        for child in Event.objects.filter(parent=event):
            update_event_path(child, event.path, event.depth)
    
    # Process all root events (events without parents)
    root_events = Event.objects.filter(parent__isnull=True)
    for root_event in root_events:
        update_event_path(root_event)


def reverse_populate_path_and_depth(apps, schema_editor):
    """Reverse migration - clear path and depth fields."""
    Event = apps.get_model('eventhub', 'Event')
    Event.objects.all().update(path='', depth=0)


class Migration(migrations.Migration):

    dependencies = [
        ('eventhub', '0005_add_path_and_depth'),
    ]

    operations = [
        migrations.RunPython(populate_path_and_depth, reverse_populate_path_and_depth),
    ]
