# Generated by Django 3.2.5 on 2021-08-11 19:40
from os import environ

from django.apps.registry import Apps
from django.db import migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor


def create_default_user_token(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    from authentik.core.models import TokenIntents

    User = apps.get_model("authentik_core", "User")
    Token = apps.get_model("authentik_core", "Token")

    db_alias = schema_editor.connection.alias

    akadmin = User.objects.using(db_alias).filter(username="akadmin")
    if not akadmin.exists():
        return
    key = None
    if "AK_ADMIN_TOKEN" in environ:
        key = environ["AK_ADMIN_TOKEN"]
    if "AUTHENTIK_BOOTSTRAP_TOKEN" in environ:
        key = environ["AUTHENTIK_BOOTSTRAP_TOKEN"]
    if not key:
        return
    Token.objects.using(db_alias).create(
        identifier="authentik-bootstrap-token",
        user=akadmin.first(),
        intent=TokenIntents.INTENT_API,
        expiring=False,
        key=key,
    )


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_core", "0026_alter_application_meta_icon"),
    ]

    operations = [
        migrations.RunPython(create_default_user_token),
    ]
