# Generated by Django 3.1.6 on 2021-02-08 18:36

import django.db.models.deletion
from django.apps.registry import Apps
from django.conf import settings
from django.db import migrations, models
from django.db.backends.base.schema import BaseDatabaseSchemaEditor

import authentik.lib.models


def migrate_from_groupmembership(apps: Apps, schema_editor: BaseDatabaseSchemaEditor):
    try:
        GroupMembershipPolicy = apps.get_model(
            "authentik_policies_group_membership", "GroupMembershipPolicy"
        )
    except LookupError:
        # GroupMembership app isn't installed, ignore migration
        return
    PolicyBinding = apps.get_model("authentik_policies", "PolicyBinding")

    db_alias = schema_editor.connection.alias

    for membership in GroupMembershipPolicy.objects.using(db_alias).all():
        for binding in PolicyBinding.objects.using(db_alias).filter(policy=membership):
            binding.group = membership.group
            binding.policy = None
            binding.save()
        membership.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("authentik_core", "0017_managed"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ("authentik_policies", "0004_policy_execution_logging"),
    ]

    operations = [
        migrations.AddField(
            model_name="policybinding",
            name="group",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to="authentik_core.group",
            ),
        ),
        migrations.AddField(
            model_name="policybinding",
            name="user",
            field=models.ForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                to=settings.AUTH_USER_MODEL,
            ),
        ),
        migrations.AlterField(
            model_name="policybinding",
            name="policy",
            field=authentik.lib.models.InheritanceForeignKey(
                blank=True,
                default=None,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="+",
                to="authentik_policies.policy",
            ),
        ),
        migrations.RunPython(migrate_from_groupmembership),
    ]
