# Generated by Django 5.0.4 on 2024-05-03 12:38

import uuid
from django.db import migrations, models
from django.apps.registry import Apps

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

from authentik.lib.migrations import progress_bar


def fix_scim_user_group_pk(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    SCIMUser = apps.get_model("authentik_providers_scim", "SCIMUser")
    SCIMGroup = apps.get_model("authentik_providers_scim", "SCIMGroup")
    db_alias = schema_editor.connection.alias
    print("\nFixing primary key for SCIM users, this might take a couple of minutes...")
    for user in progress_bar(SCIMUser.objects.using(db_alias).all()):
        SCIMUser.objects.using(db_alias).filter(
            pk=user.pk, user=user.user_id, provider=user.provider_id
        ).update(scim_id=user.pk, id=uuid.uuid4())

    print("\nFixing primary key for SCIM groups, this might take a couple of minutes...")
    for group in progress_bar(SCIMGroup.objects.using(db_alias).all()):
        SCIMGroup.objects.using(db_alias).filter(
            pk=group.pk, group=group.group_id, provider=group.provider_id
        ).update(scim_id=group.pk, id=uuid.uuid4())


class Migration(migrations.Migration):

    dependencies = [
        (
            "authentik_providers_scim",
            "0001_squashed_0006_rename_parent_group_scimprovider_filter_group",
        ),
    ]

    operations = [
        migrations.AddField(
            model_name="scimgroup",
            name="scim_id",
            field=models.TextField(default="temp"),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="scimuser",
            name="scim_id",
            field=models.TextField(default="temp"),
            preserve_default=False,
        ),
        migrations.RunPython(fix_scim_user_group_pk),
        migrations.AlterField(
            model_name="scimgroup",
            name="id",
            field=models.UUIDField(
                default=uuid.uuid4, editable=False, primary_key=True, serialize=False
            ),
        ),
        migrations.AlterField(
            model_name="scimuser",
            name="id",
            field=models.UUIDField(
                default=uuid.uuid4, editable=False, primary_key=True, serialize=False
            ),
        ),
        migrations.AlterField(model_name="scimuser", name="scim_id", field=models.TextField()),
        migrations.AlterField(model_name="scimgroup", name="scim_id", field=models.TextField()),
        migrations.AlterUniqueTogether(
            name="scimgroup",
            unique_together={("scim_id", "group", "provider")},
        ),
        migrations.AlterUniqueTogether(
            name="scimuser",
            unique_together={("scim_id", "user", "provider")},
        ),
    ]
