# Generated by Django 3.2.18 on 2023-06-22 15:08

from django.conf import settings
from django.db import migrations


def migrate_min_password_strength(apps, schema_editor):
    LoginPasswordAuthenticator = apps.get_model('authenticators', 'LoginPasswordAuthenticator')
    authenticator, _ = LoginPasswordAuthenticator.objects.get_or_create(
        slug='password-authenticator',
        defaults={'enabled': True},
    )

    password_strength = -1
    if getattr(settings, 'A2_PASSWORD_POLICY_MIN_STRENGTH', None):
        try:
            password_strength = int(settings.A2_PASSWORD_POLICY_MIN_STRENGTH)
        except (ValueError, TypeError):
            pass

        password_strength = min(password_strength, 4)

    OU = apps.get_model('a2_rbac', 'OrganizationalUnit')
    for ou in OU.objects.all():
        ou_password_strength = ou.min_password_strength if ou.min_password_strength is not None else -1
        password_strength = max(password_strength, ou_password_strength)

    if password_strength <= -1:
        password_strength = None

    authenticator.min_password_strength = password_strength
    authenticator.save()


class Migration(migrations.Migration):
    dependencies = [
        ('authenticators', '0012_loginpasswordauthenticator_min_password_strength'),
        ('a2_rbac', '0036_delete_roleattribute'),
    ]

    operations = [
        migrations.RunPython(migrate_min_password_strength, reverse_code=migrations.RunPython.noop),
    ]
