""" I added two new permission types and a new group to the management command that
creates the database on install, this creates them for existing instances """
# Generated by Django 3.2.16 on 2022-12-05 23:31

from django.db import migrations


def create_groups_and_perms(apps, schema_editor):
    """create the new "owner" group and "system admin" permission"""
    db_alias = schema_editor.connection.alias
    group_model = apps.get_model("auth", "Group")
    # Add the "owner" group, if needed
    owner_group, group_created = group_model.objects.using(db_alias).get_or_create(
        name="owner"
    )

    # Create perms, if needed
    user_model = apps.get_model("bookwyrm", "User")
    content_type_model = apps.get_model("contenttypes", "ContentType")
    content_type = content_type_model.objects.get_for_model(user_model)
    perms_model = apps.get_model("auth", "Permission")
    reg_perm, perm_created = perms_model.objects.using(db_alias).get_or_create(
        codename="manage_registration",
        name="allow or prevent user registration",
        content_type=content_type,
    )
    admin_perm, admin_perm_created = perms_model.objects.using(db_alias).get_or_create(
        codename="system_administration",
        name="technical controls",
        content_type=content_type,
    )

    # Add perms to the group if anything was created
    if group_created or perm_created or admin_perm_created:
        perms = [
            "edit_instance_settings",
            "set_user_group",
            "control_federation",
            "create_invites",
            "moderate_user",
            "moderate_post",
            "edit_book",
        ]
        owner_group.permissions.set(
            perms_model.objects.using(db_alias).filter(codename__in=perms).all()
        )

        # also extend these perms to admins
        # This is get or create so the tests don't fail -- it should already exist
        admin_group, _ = group_model.objects.using(db_alias).get_or_create(name="admin")
        admin_group.permissions.add(reg_perm)
        admin_group.permissions.add(admin_perm)


class Migration(migrations.Migration):

    dependencies = [
        ("bookwyrm", "0167_auto_20221125_1900"),
    ]

    operations = [
        migrations.RunPython(create_groups_and_perms, migrations.RunPython.noop)
    ]
