# Generated by Django 4.2.23 on 2025-06-30 12:48

import logging

from django.db import migrations


logger = logging.getLogger(__name__)


def migrate_content_type_forward_noop(apps, schema_editor):
    """Forward no-op: data migration already happened in 0005."""
    pass


def migrate_content_type_reverse(apps, schema_editor):
    """Reverse migration: undo what 0005 did by copying data back from new_content_type to content_type.
    
    When this reverse runs, we're going from state after 0005 back to state after 0004.
    After 0005: data was copied from content_type to new_content_type
    To reverse: copy from new_content_type back to content_type, and clear new_content_type
    """
    django_ct_cls = apps.get_model('contenttypes', 'ContentType')
    
    for model_name in ('dabpermission', 'objectrole', 'roledefinition', 'roleuserassignment', 'roleteamassignment'):
        cls = apps.get_model('dab_rbac', model_name)
        update_ct = 0
        for obj in cls.objects.all():
            new_ct = obj.new_content_type
            if new_ct:
                try:
                    # Find the corresponding Django ContentType by app_label and model
                    django_ct = django_ct_cls.objects.get(app_label=new_ct.app_label, model=new_ct.model)
                except Exception as e:
                    raise RuntimeError(
                        f"Failed to get Django content type for a {model_name} pk={obj.pk}, "
                        f"DABContentType app_label='{new_ct.app_label}', model='{new_ct.model}'"
                    ) from e
                obj.content_type = django_ct
                obj.save()
                update_ct += 1
        if update_ct:
            logger.info(f'Reverse-migrated content_type reference to old model for {model_name} for {update_ct} entries')


class Migration(migrations.Migration):

    dependencies = [
        ('dab_rbac', '0005_remote_permissions_data'),
    ]

    operations = [
        migrations.RunPython(migrate_content_type_forward_noop, migrate_content_type_reverse),
    ] 