# Generated by Django 3.2.14 on 2022-08-16 03:32
from django.db import migrations, models


def migrate_system_user_to_accounts(apps, schema_editor):
    asset_permission_model = apps.get_model("perms", "AssetPermission")

    count = 0
    bulk_size = 10000
    while True:
        asset_permissions = asset_permission_model.objects \
            .prefetch_related('system_users')[count:bulk_size]
        if not asset_permissions:
            break

        count += len(asset_permissions)
        updated = []
        for asset_permission in asset_permissions:
            asset_permission.accounts = [s.username for s in asset_permission.system_users.all()]
            updated.append(asset_permission)
        asset_permission_model.objects.bulk_update(updated, ['accounts'])


class Migration(migrations.Migration):

    dependencies = [
        ('perms', '0029_auto_20220728_1728'),
    ]

    operations = [
        migrations.AddField(
            model_name='assetpermission',
            name='accounts',
            field=models.JSONField(default=list, verbose_name='Account'),
        ),
        migrations.RunPython(migrate_system_user_to_accounts),
        migrations.RemoveField(
            model_name='assetpermission',
            name='system_users',
        ),
    ]
