# Generated by Django 4.2.7 on 2024-03-31 16:15

from django.db import migrations


from django.contrib.auth.models import Group, Permission


def update_groups_permissions(apps, schema_editor):
    # first add a missing role
    user_roles = ["Moderator"]

    for name in user_roles:
        Group.objects.create(name=name)

    all_perms = Permission.objects.all()

    # set permissions for moderators
    moderator_perms = [i for i in all_perms if i.content_type.app_label == 'agenda_culturel' and i.content_type.model in ['event', 'duplicatedevents']]
    Group.objects.get(name="Moderator").permissions.add(*moderator_perms)

    read_mod_perms = [i for i in moderator_perms if i.codename.startswith('view_')]

    # set permissions for automation managers
    automanager_perms = [i for i in all_perms if i.content_type.app_label == 'agenda_culturel' and i.content_type.model in ['batchimportation', 'recurrentimport', 'categorisationrule']]
    Group.objects.get(name="Automation Manager").permissions.add(*automanager_perms)
    Group.objects.get(name="Automation Manager").permissions.add(*read_mod_perms)

    # set permissions for receptionists
    receptionist_perms = [i for i in all_perms if i.content_type.app_label == 'agenda_culturel' and i.content_type.model in ['contactmessage']]
    Group.objects.get(name="Receptionist").permissions.add(*receptionist_perms)
    Group.objects.get(name="Receptionist").permissions.add(*read_mod_perms)

def update_groups_delete(apps, schema_editor):
    user_roles = ["Moderator"]

    for name in user_roles:
        Group.objects.filter(name=name).delete()



class Migration(migrations.Migration):

    dependencies = [
        ('agenda_culturel', '0037_alter_batchimportation_options_and_more'),
    ]

    operations = [
        migrations.RunPython(update_groups_permissions, reverse_code=update_groups_delete),
    ]
