# Generated by Django 3.2.11 on 2022-01-31 13:22

from django.db import migrations, transaction


def move_content_guards_up(apps, schema_editor, up=True):
    SourceContentRedirectContentGuard = apps.get_model("container", "ContentRedirectContentGuard")
    DestContentRedirectContentGuard = apps.get_model("core", "ContentRedirectContentGuard")

    if up:
        dest_pulp_type = "core.content_redirect"
    else:
        dest_pulp_type = "container.content_redirect"
        SourceContentRedirectContentGuard, DestContentRedirectContentGuard = DestContentRedirectContentGuard, SourceContentRedirectContentGuard

    for content_guard in SourceContentRedirectContentGuard.objects.all():
        with transaction.atomic():
            new_content_guard = DestContentRedirectContentGuard(
                pulp_id=content_guard.pulp_id,
                pulp_created=content_guard.pulp_created,
                pulp_last_updated=content_guard.pulp_last_updated,
                pulp_type=dest_pulp_type,
                name=content_guard.name,
                description=content_guard.description,
                shared_secret=content_guard.shared_secret,
            )
            distributions = list(content_guard.distribution_set.all())
            content_guard.delete()
            new_content_guard.save()
            new_content_guard.distribution_set.set(distributions)


def move_content_guards_down(apps, schema_editor):
    move_content_guards_up(apps, schema_editor, up=False)


class Migration(migrations.Migration):

    dependencies = [
        ('container', '0020_update_push_repo_perms'),
        ('core', '0085_contentredirectcontentguard'),
    ]

    operations = [
        migrations.RunPython(code=move_content_guards_up, reverse_code=move_content_guards_down, elidable=True),
    ]
