# Generated by Django 5.1.5 on 2025-02-23 10:11

from django.db import migrations, models


def migrate_annotations_values(apps, schema_editor):
    """Migrate annotation values to use deleted field.

    We have to:
    - set deleted field to True for all non-latest annotation values.
    - remove all delete markers (values with value=None).
    """
    AnnotationValue = apps.get_model("flow", "AnnotationValue")
    # Set deleted field to True for all non-latest annotation values.
    to_update_ids = list(
        AnnotationValue.objects.all()
        .annotate(
            rank=models.Window(
                expression=models.functions.DenseRank(),
                partition_by=[models.F("field"), models.F("entity")],
                order_by=models.F("created").desc(),
            ),
        )
        .filter(rank__gt=1)
        .values_list("id", flat=True)
    )
    AnnotationValue.objects.filter(id__in=to_update_ids).update(deleted=True)

    # Now remove all delete markers. This is done in couple steps:
    # 1. Save their ids.
    # 2. Set their values to something non-null (otherwise delete will fail).
    # 3. Delete them.
    to_delete_ids = AnnotationValue.objects.filter(
        models.Q(_value__isnull=True) | models.Q(_value__value__isnull=True)
    ).values_list("id", flat=True)
    AnnotationValue.objects.filter(id__in=to_delete_ids).update(
        _value={"value": "to_delete", "label": "to_delete"}
    )
    AnnotationValue.objects.filter(id__in=to_delete_ids).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("flow", "0036_annotationvalue_deleted"),
    ]

    operations = [
        migrations.RunPython(migrate_annotations_values),
    ]
