# Generated by Django 3.1.8 on 2021-05-28 09:24

from django.db import migrations, models
from django.contrib.postgres.aggregates import ArrayAgg


def remove_non_unique_announcement_and_recipient_activities(apps, schema_editor):
    Activity = apps.get_model("activity", "Activity")
    duplicates = (
        Activity.objects.filter(type="announcement")
        .values_list("recipient_id", "announcement_id")
        .order_by()
        .annotate(count=models.Count("id"))
        .annotate(ids=ArrayAgg("id"))
        .filter(count__gt=1)
        .values_list("ids", flat=True)
    )
    duplicate_ids = sum([ids[1:] for ids in duplicates], [])
    Activity.objects.filter(pk__in=duplicate_ids).delete()


def reverse_remove_non_unique_announcement_and_recipient_activities(
    apps, schema_editor
):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("activity", "0018_add_link_label_field_to_announcement"),
    ]

    operations = [
        migrations.RunPython(
            remove_non_unique_announcement_and_recipient_activities,
            reverse_remove_non_unique_announcement_and_recipient_activities,
            atomic=True,
        ),
        migrations.AddConstraint(
            model_name="activity",
            constraint=models.UniqueConstraint(
                condition=models.Q(type="announcement"),
                fields=("recipient", "announcement"),
                name="unique_for_recipient_and_announcement",
            ),
        ),
    ]
