# Generated by Django 5.0.9 on 2024-10-17 07:58

from django.db import migrations
from django.db.models import Count


def remove_duplicates(apps, schema_editor):
    RuleCheckedObjectRelationship = apps.get_model("wbcompliance", "RuleCheckedObjectRelationship")
    for row in (
        RuleCheckedObjectRelationship.objects.values("rule", "checked_object_content_type", "checked_object_id")
        .annotate(c=Count("*"))
        .filter(c__gt=1)
    ):
        qs = RuleCheckedObjectRelationship.objects.filter(
            rule=row["rule"],
            checked_object_content_type=row["checked_object_content_type"],
            checked_object_id=row["checked_object_id"],
        )
        base = qs.first()
        for rel in qs.exclude(id=base.id):
            rel.checks.update(rule_checked_object_relationship=rel)
            rel.delete()


class Migration(migrations.Migration):
    dependencies = [
        ("contenttypes", "0002_remove_content_type_name"),
        ("wbcompliance", "0017_alter_rulebackend_incident_report_template"),
    ]

    operations = [
        migrations.RunSQL(sql="SET CONSTRAINTS ALL IMMEDIATE;"),
        migrations.RunPython(remove_duplicates),
        migrations.RunSQL(sql="SET CONSTRAINTS ALL DEFERRED;"),
        migrations.AlterUniqueTogether(
            name="rulecheckedobjectrelationship",
            unique_together={("rule", "checked_object_content_type", "checked_object_id")},
        ),
    ]
