"""
Data migration to convert orphaned staff resources to room type.

Staff type resources MUST have an assigned staff member (user FK).
Any existing staff resources without a user are invalid and should be
converted to ROOM type (or OTHER category for resource_type).
"""
from django.db import migrations


def convert_orphaned_staff_resources(apps, schema_editor):
    """
    Find staff resources without assigned users and convert them to room type.
    This handles both the legacy 'type' field and new 'resource_type' FK.
    """
    Resource = apps.get_model('schedule', 'Resource')
    ResourceType = apps.get_model('schedule', 'ResourceType')

    # Find all staff resources without a user assigned
    # Check legacy type field
    orphaned_legacy = Resource.objects.filter(
        type='STAFF',
        user__isnull=True
    )

    legacy_count = orphaned_legacy.count()
    if legacy_count > 0:
        print(f"\n  Converting {legacy_count} orphaned staff resources (legacy type field) to ROOM type...")
        orphaned_legacy.update(type='ROOM')

    # Check new resource_type with STAFF category
    orphaned_new = Resource.objects.filter(
        resource_type__category='STAFF',
        user__isnull=True
    )

    new_count = orphaned_new.count()
    if new_count > 0:
        print(f"\n  Converting {new_count} orphaned staff resources (new resource_type) to OTHER category...")
        # Try to find or create a "Room" resource type with OTHER category
        room_type = ResourceType.objects.filter(
            category='OTHER',
            is_default=True
        ).first()

        if room_type:
            orphaned_new.update(resource_type=room_type)
        else:
            # If no default OTHER type exists, just clear the resource_type
            # and set legacy type to ROOM
            orphaned_new.update(resource_type=None, type='ROOM')

    total = legacy_count + new_count
    if total > 0:
        print(f"  Total: {total} orphaned staff resources converted.")
    else:
        print("\n  No orphaned staff resources found.")


def reverse_migration(apps, schema_editor):
    """
    Reverse is not possible - we cannot know which resources were originally
    staff type. This migration is intentionally one-way.
    """
    pass  # No-op, cannot reverse


class Migration(migrations.Migration):

    dependencies = [
        ('schedule', '0030_time_block_approval'),
    ]

    operations = [
        migrations.RunPython(
            convert_orphaned_staff_resources,
            reverse_code=reverse_migration
        ),
    ]
