# Generated by Django 3.1.1 on 2020-09-17 11:55
from django.apps.registry import Apps
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor

import passbook.audit.models


def convert_user_to_json(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    Event = apps.get_model("passbook_audit", "Event")

    db_alias = schema_editor.connection.alias
    for event in Event.objects.all():
        event.delete()
        # Because event objects cannot be updated, we have to re-create them
        event.pk = None
        event.user_json = (
            passbook.audit.models.get_user(event.user) if event.user else {}
        )
        event._state.adding = True
        event.save()


class Migration(migrations.Migration):

    dependencies = [
        ("passbook_audit", "0002_auto_20200918_2116"),
    ]

    operations = [
        migrations.AlterField(
            model_name="event",
            name="action",
            field=models.TextField(
                choices=[
                    ("LOGIN", "login"),
                    ("LOGIN_FAILED", "login_failed"),
                    ("LOGOUT", "logout"),
                    ("AUTHORIZE_APPLICATION", "authorize_application"),
                    ("SUSPICIOUS_REQUEST", "suspicious_request"),
                    ("SIGN_UP", "sign_up"),
                    ("PASSWORD_RESET", "password_reset"),
                    ("INVITE_CREATED", "invitation_created"),
                    ("INVITE_USED", "invitation_used"),
                    ("IMPERSONATION_STARTED", "impersonation_started"),
                    ("IMPERSONATION_ENDED", "impersonation_ended"),
                    ("CUSTOM", "custom"),
                ]
            ),
        ),
        migrations.AddField(
            model_name="event",
            name="user_json",
            field=models.JSONField(default=dict),
        ),
        migrations.RunPython(convert_user_to_json),
        migrations.RemoveField(
            model_name="event",
            name="user",
        ),
        migrations.RenameField(
            model_name="event", old_name="user_json", new_name="user"
        ),
    ]