# Generated by Django 3.1.1 on 2020-09-25 15:36

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

from authentik.flows.models import FlowDesignation
from authentik.stages.authenticator_totp.models import TOTPDigits


def create_default_setup_flow(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    Flow = apps.get_model("authentik_flows", "Flow")
    FlowStageBinding = apps.get_model("authentik_flows", "FlowStageBinding")

    AuthenticatorTOTPStage = apps.get_model(
        "authentik_stages_authenticator_totp", "AuthenticatorTOTPStage"
    )

    db_alias = schema_editor.connection.alias

    flow, _ = Flow.objects.using(db_alias).update_or_create(
        slug="default-authenticator-totp-setup",
        designation=FlowDesignation.STAGE_CONFIGURATION,
        defaults={
            "name": "default-authenticator-totp-setup",
            "title": "Setup Two-Factor authentication",
        },
    )

    stage, _ = AuthenticatorTOTPStage.objects.using(db_alias).update_or_create(
        name="default-authenticator-totp-setup", defaults={"digits": TOTPDigits.SIX}
    )

    FlowStageBinding.objects.using(db_alias).update_or_create(
        target=flow, stage=stage, defaults={"order": 0}
    )

    for stage in AuthenticatorTOTPStage.objects.using(db_alias).filter(
        configure_flow=None
    ):
        stage.configure_flow = flow
        stage.save()


class Migration(migrations.Migration):

    dependencies = [
        (
            "authentik_stages_authenticator_totp",
            "0005_auto_20210216_0838",
        ),
    ]

    operations = [
        migrations.RunPython(create_default_setup_flow),
    ]
