# Generated by Django 3.1.7 on 2021-03-23 22:09

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

from authentik.flows.models import FlowDesignation


def create_default_pre_authentication_flow(
    apps: Apps, schema_editor: BaseDatabaseSchemaEditor
):
    Flow = apps.get_model("authentik_flows", "Flow")
    SAMLSource = apps.get_model("authentik_sources_saml", "samlsource")

    db_alias = schema_editor.connection.alias

    # Empty flow for providers where consent is implicitly given
    flow, _ = Flow.objects.using(db_alias).update_or_create(
        slug="default-source-pre-authentication",
        designation=FlowDesignation.STAGE_CONFIGURATION,
        defaults={"name": "Pre-Authentication", "title": ""},
    )

    for source in SAMLSource.objects.using(db_alias).all():
        source.pre_authentication_flow = flow
        source.save()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_flows", "0016_auto_20201202_1307"),
        ("authentik_sources_saml", "0009_auto_20210301_0949"),
    ]

    operations = [
        migrations.AddField(
            model_name="samlsource",
            name="pre_authentication_flow",
            field=models.ForeignKey(
                default=None,
                null=True,
                help_text="Flow used before authentication.",
                on_delete=django.db.models.deletion.CASCADE,
                related_name="source_pre_authentication",
                to="authentik_flows.flow",
            ),
            preserve_default=False,
        ),
        migrations.RunPython(create_default_pre_authentication_flow),
    ]
