# Generated by Django 2.2.19 on 2021-09-14 18:54

from django.db import migrations
from django.db.models import Count


def migrate_issuer_forward(apps, schema_editor):
    UserSAMLIdentifier = apps.get_model('mellon', 'UserSAMLIdentifier')
    Issuer = apps.get_model('mellon', 'Issuer')
    issuers = UserSAMLIdentifier.objects.values_list('issuer').annotate(total=Count('id'))
    for issuer, total in issuers:
        issuer_instance = Issuer.objects.create(entity_id=issuer)
        UserSAMLIdentifier.objects.filter(issuer=issuer).update(issuer_fk=issuer_instance)


def migrate_issuer_backward(apps, schema_editor):
    UserSAMLIdentifier = apps.get_model('mellon', 'UserSAMLIdentifier')
    Issuer = apps.get_model('mellon', 'Issuer')
    for issuer in Issuer.objects.all():
        UserSAMLIdentifier.objects.filter(issuer_fk=issuer).update(issuer=issuer.entity_id)


class Migration(migrations.Migration):
    dependencies = [
        ('mellon', '0003_add_issuer_model'),
    ]

    operations = []
    operations = [
        migrations.RunPython(migrate_issuer_forward, migrate_issuer_backward),
    ]
