# Generated by Django 3.2.15 on 2022-08-29 11:04

from django.db import migrations
import pulpcore.app.models.fields


def encrypt_remote_fields(apps, schema_editor):
    CollectionRemote = apps.get_model("ansible", "CollectionRemote")

    remotes_needing_update = []
    for remote in CollectionRemote.objects.order_by("pulp_id").iterator():
        remote._encrypted_token = remote.token
        remotes_needing_update.append(remote)

        if len(remotes_needing_update) > 100:
            CollectionRemote.objects.bulk_update(remotes_needing_update, ("_encrypted_token",))
            remotes_needing_update.clear()

    CollectionRemote.objects.bulk_update(remotes_needing_update, ("_encrypted_token",))


def unencrypt_remote_fields(apps, schema_editor):
    CollectionRemote = apps.get_model("ansible", "CollectionRemote")

    remotes_needing_update = []
    for remote in CollectionRemote.objects.order_by("pulp_id").iterator():
        remote.token = remote._encrypted_token
        remotes_needing_update.append(remote)

        if len(remotes_needing_update) > 100:
            CollectionRemote.objects.bulk_update(remotes_needing_update, ("token",))
            remotes_needing_update.clear()

    CollectionRemote.objects.bulk_update(remotes_needing_update, ("token",))


class Migration(migrations.Migration):

    dependencies = [
        ('ansible', '0043_alter_collectionversionsignature_data'),
    ]

    operations = [
        # Add new fields to temporarily hold the encrypted values
        migrations.AddField(
            model_name="collectionremote",
            name="_encrypted_token",
            field=pulpcore.app.models.fields.EncryptedTextField(null=True),
        ),
        # Populate the new fields with encrypted values computed from the unencrypted fields
        migrations.RunPython(
            code=encrypt_remote_fields,
            reverse_code=unencrypt_remote_fields,
            elidable=True,
        ),
        # Remove the unencrypted columns
        migrations.RemoveField(
            model_name="collectionremote",
            name="token",
        ),
        # Replace the formerly-unencrypted columns with the new encrypted ones
        migrations.RenameField(
            model_name="collectionremote",
            old_name="_encrypted_token",
            new_name="token",
        ),
    ]
