# Generated by Django 4.2.6 on 2023-10-28 14:24

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


def set_oobe_flow_authentication(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    from guardian.shortcuts import get_anonymous_user

    Flow = apps.get_model("authentik_flows", "Flow")
    User = apps.get_model("authentik_core", "User")

    db_alias = schema_editor.connection.alias

    users = User.objects.using(db_alias).exclude(username="akadmin")
    try:
        users = users.exclude(pk=get_anonymous_user().pk)
    # pylint: disable=broad-except
    except Exception:  # nosec
        pass

    if users.exists():
        Flow.objects.filter(slug="initial-setup").update(authentication="require_superuser")


class Migration(migrations.Migration):
    dependencies = [
        ("authentik_flows", "0026_alter_flow_options"),
    ]

    operations = [
        migrations.RunPython(set_oobe_flow_authentication),
    ]
