# Generated by Django 3.2.22 on 2023-11-06 22:56

from django.db import migrations


def remove_dangling_note_objects(apps, schema_editor):
    """
    Remove Note objects associated with deleted objects.
    """
    Note = apps.get_model("extras", "Note")
    print("\n>>> Finding and removing any invalid or dangling Note objects ...\n")
    model_class = None
    assigned_object_type_id = None
    deleted_count = 0
    for note in Note.objects.order_by("assigned_object_type").iterator():
        # cache model_class and assigned_object_type_id
        if note.assigned_object_type_id != assigned_object_type_id:
            try:
                model_class = apps.get_model(note.assigned_object_type.app_label, note.assigned_object_type.model)
            except LookupError:
                model_class = None
            assigned_object_type_id = note.assigned_object_type_id
        if model_class is None or not model_class.objects.filter(id=note.assigned_object_id).exists():
            note.delete()
            deleted_count += 1
    if deleted_count > 0:
        print(f"\n>>> Removed {deleted_count} invalid or dangling Note objects. \n")
    print("\n>>> Removal completed. \n")


class Migration(migrations.Migration):
    dependencies = [
        ("extras", "0098_rename_data_jobresult_result"),
    ]

    operations = [
        migrations.RunPython(remove_dangling_note_objects, migrations.RunPython.noop),
    ]
