# Generated by Django 5.0.9 on 2024-11-04 12:56
from dataclasses import asdict
from django.apps.registry import Apps

from django.db.backends.base.schema import BaseDatabaseSchemaEditor

from django.db import migrations, models


def migrate_redirect_uris(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    from authentik.providers.oauth2.models import RedirectURI, RedirectURIMatchingMode

    OAuth2Provider = apps.get_model("authentik_providers_oauth2", "oauth2provider")

    db_alias = schema_editor.connection.alias
    for provider in OAuth2Provider.objects.using(db_alias).all():
        uris = []
        for old in provider.old_redirect_uris.split("\n"):
            mode = RedirectURIMatchingMode.STRICT
            if old == "*" or old == ".*":
                mode = RedirectURIMatchingMode.REGEX
            uris.append(asdict(RedirectURI(mode, url=old)))
        provider._redirect_uris = uris
        provider.save()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_providers_oauth2", "0023_alter_accesstoken_refreshtoken_use_hash_index"),
    ]

    operations = [
        migrations.RenameField(
            model_name="oauth2provider",
            old_name="redirect_uris",
            new_name="old_redirect_uris",
        ),
        migrations.AddField(
            model_name="oauth2provider",
            name="_redirect_uris",
            field=models.JSONField(default=dict, verbose_name="Redirect URIs"),
        ),
        migrations.RunPython(migrate_redirect_uris, lambda *args: ...),
        migrations.RemoveField(
            model_name="oauth2provider",
            name="old_redirect_uris",
        ),
    ]
