# Generated by Django 3.1.12 on 2021-08-26 09:59

from django.db import migrations, transaction
from django.db.models import F


def migrate_app_account(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    app_perm_model = apps.get_model("perms", "ApplicationPermission")
    app_account_model = apps.get_model("applications", 'Account')

    queryset = app_perm_model.objects \
        .exclude(system_users__isnull=True) \
        .exclude(applications__isnull=True) \
        .annotate(systemuser=F('system_users')) \
        .annotate(app=F('applications')) \
        .values('app', 'systemuser', 'org_id')

    accounts = []
    for p in queryset:
        if not p['app']:
            continue
        account = app_account_model(
            app_id=p['app'], systemuser_id=p['systemuser'],
            version=1, org_id=p['org_id']
        )
        accounts.append(account)

    app_account_model.objects.using(db_alias).bulk_create(accounts, ignore_conflicts=True)


class Migration(migrations.Migration):

    dependencies = [
        ('applications', '0010_appaccount_historicalappaccount'),
    ]

    operations = [
        migrations.RunPython(migrate_app_account)
    ]
