# Generated by Django 5.0.11 on 2025-01-27 12:59

from django.db import migrations
import django.db.models.deletion
from django.db import migrations, models


def migrate_sessions(apps, schema_editor):
    ConnectionToken = apps.get_model("authentik_providers_rac", "ConnectionToken")
    AuthenticatedSession = apps.get_model("authentik_core", "AuthenticatedSession")
    db_alias = schema_editor.connection.alias

    for token in ConnectionToken.objects.using(db_alias).all():
        token.session = (
            AuthenticatedSession.objects.using(db_alias)
            .filter(session__session_key=token.old_session.session_key)
            .first()
        )
        if token.session:
            token.save()
        else:
            token.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_providers_rac", "0006_connectiontoken_authentik_p_expires_91f148_idx_and_more"),
        ("authentik_core", "0046_session_and_more"),
    ]

    operations = [
        migrations.RenameField(
            model_name="connectiontoken",
            old_name="session",
            new_name="old_session",
        ),
        migrations.AddField(
            model_name="connectiontoken",
            name="session",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="authentik_core.authenticatedsession",
            ),
        ),
        migrations.RunPython(code=migrate_sessions),
        migrations.AlterField(
            model_name="connectiontoken",
            name="session",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                to="authentik_core.authenticatedsession",
            ),
        ),
        migrations.RemoveField(
            model_name="connectiontoken",
            name="old_session",
        ),
    ]
