# Generated by Django 3.2.9 on 2022-08-13 05:33
from django.contrib.auth.models import Group, Permission
from django.conf import settings
import logging

from django.db import migrations

logger = logging.getLogger(__name__)

public_group_permissions = {
    settings.DEFAULT_PERMISSIONS_GROUP: [
        "create_column",
        "read_column",
        "update_column",
        "delete_column",
        "permission_column",

        "create_fieldset",
        "read_fieldset",
        "update_fieldset",
        "delete_fieldset",
        "permission_fieldset",

        "create_extract",
        "read_extract",
        "update_extract",
        "delete_extract",
        "permission_extract",

        "create_datacell",
        "read_datacell",
        "update_datacell",
        "delete_datacell",
        "permission_datacell",
    ]
}


def add_group_permissions(apps, schema_editor):
    """Assign extract-related permissions to the public group if present.

    Do not emit post_migrate here; rely on Django's normal signal.
    Skip missing permissions silently to avoid brittle ordering.
    """

    for group in public_group_permissions:
        role, created = Group.objects.get_or_create(name=group)
        logger.info(f'{group} Group created')
        for perm in public_group_permissions[group]:
            try:
                logger.info(f'Permitting {group} to {perm}')
                role.permissions.add(Permission.objects.get(codename=perm))
            except Permission.DoesNotExist:
                logger.warning(f"Permission '{perm}' does not exist yet; skipping assignment.")
        role.save()

    logger.info("Installation of default public access group COMPLETE!")


class Migration(migrations.Migration):
    dependencies = [
        ('users', '0008_alter_userexport_format'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]
