# Generated by Django 3.2.18 on 2023-06-13 13:17

import logging

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

logger = logging.getLogger('authentic2.authenticators')


def get_setting(name, default, max_length=None):
    setting = getattr(settings, name, default)

    expected_type = type(default)

    if expected_type in (float, int) and isinstance(setting, (float, int)):
        pass
    elif not isinstance(setting, expected_type):
        setting = None

    if setting is None:
        setting = default

    return setting[:max_length] if max_length else setting


def update_authenticator(qs):
    qs.update(
        password_min_length=get_setting('A2_PASSWORD_POLICY_MIN_LENGTH', default=8),
        password_regex=get_setting('A2_PASSWORD_POLICY_REGEX', default='', max_length=512),
        password_regex_error_msg=get_setting(
            'A2_PASSWORD_POLICY_REGEX_ERROR_MSG', default='', max_length=1024
        ),
        login_exponential_retry_timeout_duration=get_setting(
            'A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_DURATION',
            default=1.0,
        ),
        login_exponential_retry_timeout_factor=get_setting(
            'A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_FACTOR',
            default=1.8,
        ),
        login_exponential_retry_timeout_max_duration=get_setting(
            'A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MAX_DURATION', default=3600
        ),
        login_exponential_retry_timeout_min_duration=get_setting(
            'A2_LOGIN_EXPONENTIAL_RETRY_TIMEOUT_MIN_DURATION', default=10
        ),
        emails_ip_ratelimit=get_setting('A2_EMAILS_IP_RATELIMIT', default='10/h', max_length=32),
        sms_ip_ratelimit=get_setting('A2_SMS_IP_RATELIMIT', default='10/h', max_length=32),
        emails_address_ratelimit=get_setting('A2_EMAILS_ADDRESS_RATELIMIT', default='3/d', max_length=32),
        sms_number_ratelimit=get_setting('A2_SMS_NUMBER_RATELIMIT', default='10/h', max_length=32),
    )


def migrate_password_settings(apps, schema_editor):
    LoginPasswordAuthenticator = apps.get_model('authenticators', 'LoginPasswordAuthenticator')
    authenticator = LoginPasswordAuthenticator.objects.get_or_create(
        slug='password-authenticator',
        defaults={'enabled': True},
    )[0]
    qs = LoginPasswordAuthenticator.objects.filter(pk=authenticator.pk)

    try:
        with transaction.atomic():
            update_authenticator(qs)
    except Exception:
        logger.exception('error on login password authenticator settings migration')


class Migration(migrations.Migration):
    dependencies = [
        ('authenticators', '0008_new_password_settings_fields'),
    ]

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