# Generated by Django 3.2.12 on 2022-03-15 12:15

from django.conf import settings
from django.db import migrations
from django.db.models import Count, Min


def remove_duplicate_entries(apps, schema_editor):
    SystemWideEnterpriseUserRoleAssignment = apps.get_model('enterprise', 'SystemWideEnterpriseUserRoleAssignment')

    duplicates = (
        SystemWideEnterpriseUserRoleAssignment.objects.values('user_id', 'role_id', 'enterprise_customer_id')
            .annotate(first_entry_id=Min('id'), num_entries=Count('id'))
            .filter(num_entries__gt=1)
    )

    # delete the duplicates, excluding the first role assignment for the user/role/enterprise combination
    for duplicate in duplicates:
        (
            SystemWideEnterpriseUserRoleAssignment.objects
                .filter(
                    user_id=duplicate['user_id'],
                    role_id=duplicate['role_id'],
                    enterprise_customer_id=duplicate['enterprise_customer_id']
                )
                .exclude(id=duplicate['first_entry_id'])
                .delete()
        )


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('enterprise', '0153_add_enable_browse_and_request'),
    ]

    operations = [
        migrations.RunPython(remove_duplicate_entries, reverse_code=migrations.RunPython.noop),
        migrations.AlterUniqueTogether(
            name='systemwideenterpriseuserroleassignment',
            unique_together={('enterprise_customer', 'role', 'user')},
        ),
    ]
