# Generated by Django 2.2.19 on 2021-02-26 10:02

from django.db import migrations

from authentic2 import app_settings


def delete_users(apps, schema_editor):
    # to run schema and data altering statements in the same transaction, you
    # must execute all constraints/triggers immediately, likely caused by
    # on_cascade=models.DELETE
    schema_editor.execute('SET CONSTRAINTS ALL IMMEDIATE')
    User = apps.get_model('custom_user', 'User')
    DeletedUser = apps.get_model('custom_user', 'DeletedUser')

    def delete_user(self):
        deleted_user = DeletedUser(old_user_id=self.id)
        if 'email' in app_settings.A2_USER_DELETED_KEEP_DATA:
            deleted_user.old_email = self.email.rsplit('#', 1)[0]
        if 'uuid' in app_settings.A2_USER_DELETED_KEEP_DATA:
            deleted_user.old_uuid = self.uuid

        # save LDAP account references
        external_ids = self.userexternalid_set.order_by('id')
        if external_ids.exists():
            deleted_user.old_data = {'external_ids': []}
            for external_id in external_ids:
                deleted_user.old_data['external_ids'].append(
                    {
                        'source': external_id.source,
                        'external_id': external_id.external_id,
                    }
                )
            external_ids.delete()
        deleted_user.save()
        self.delete()

    for user in User.objects.filter(deleted__isnull=False):
        delete_user(user)


class Migration(migrations.Migration):

    dependencies = [
        ('custom_user', '0025_user_deactivation'),
    ]

    operations = [
        migrations.RunPython(delete_users, migrations.RunPython.noop),
        migrations.RemoveField(
            model_name='user',
            name='deleted',
        ),
    ]
