# Generated by Django 2.2.28 on 2022-04-13 14:22

from django.conf import settings
from django.db import migrations
from django.utils.text import slugify


def add_base_authenticators(apps, schema_editor):
    kwargs_settings = getattr(settings, 'AUTH_FRONTENDS_KWARGS', {})
    oidc_provider_settings = kwargs_settings.get('oidc', {})
    show_condition = oidc_provider_settings.get('show_condition') or ''

    BaseAuthenticator = apps.get_model('authenticators', 'BaseAuthenticator')
    OIDCProvider = apps.get_model('authentic2_auth_oidc', 'OIDCProvider')
    OIDCClaimMapping = apps.get_model('authentic2_auth_oidc', 'OIDCClaimMapping')
    OIDCAccount = apps.get_model('authentic2_auth_oidc', 'OIDCAccount')

    remap_provider_ids = []
    for provider in OIDCProvider.objects.all():
        if isinstance(show_condition, dict):
            show_condition_authenticator = show_condition.get(provider.slug) or ''
        else:
            show_condition_authenticator = show_condition

        base_authenticator = BaseAuthenticator.objects.create(
            name=provider.name,
            slug=provider.slug or slugify(provider.name),
            ou=provider.ou,
            enabled=provider.show and getattr(settings, 'A2_AUTH_OIDC_ENABLE', True),
            order=oidc_provider_settings.get('priority', 2),
            show_condition=show_condition_authenticator,
        )
        provider.baseauthenticator_ptr = base_authenticator.pk
        provider.save()

        remap_provider_ids.append(
            (
                list(OIDCClaimMapping.objects.filter(provider=provider.pk).values_list('pk', flat=True)),
                list(OIDCAccount.objects.filter(provider=provider.pk).values_list('pk', flat=True)),
                base_authenticator.pk,
            )
        )

    for mapping_ids, account_ids, to_provider_id in remap_provider_ids:
        OIDCClaimMapping.objects.filter(id__in=mapping_ids).update(provider=to_provider_id)
        OIDCAccount.objects.filter(id__in=account_ids).update(provider=to_provider_id)


class Migration(migrations.Migration):
    dependencies = [
        ('authentic2_auth_oidc', '0009_oidcprovider_baseauthenticator_ptr'),
        ('authenticators', '0001_initial'),
    ]

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