# Generated by Django 5.0.3 on 2024-04-23 09:36

from django.db import migrations, models


def handle_existing_duplicates(apps, schema_editor):
    Fees = apps.get_model("wbportfolio", "Fees")

    # we delete any fees with non unique lookup with same total value, this is safe
    for row in (
        Fees.objects.values("linked_product", "fee_date", "transaction_subtype", "calculated", "total_value")
        .annotate(c=models.Count("*"))
        .filter(c__gt=1)
    ):
        row.pop("c")
        for f in Fees.objects.filter(**row)[1:]:
            f.delete()
    # we dinstiguly delete duplicates only for calculated fees and keep the last inserted
    for row in (
        Fees.objects.filter(calculated=True)
        .values("linked_product", "fee_date", "transaction_subtype", "calculated")
        .annotate(c=models.Count("*"))
        .filter(c__gt=1)
    ):
        row.pop("c")
        for f in Fees.objects.filter(**row).order_by("-id")[1:]:
            f.delete()

    # we shouldn't have any duplicates (particularly non calculated fees) at this point


class Migration(migrations.Migration):
    dependencies = [
        ("wbportfolio", "0058_pmsinstrument"),
    ]

    operations = [
        migrations.RunSQL(
            sql="SET CONSTRAINTS ALL IMMEDIATE;",
        ),
        migrations.RunPython(handle_existing_duplicates),
        migrations.RunSQL(
            sql="SET CONSTRAINTS ALL DEFERRED;",
        ),
        migrations.AddConstraint(
            model_name="fees",
            constraint=models.UniqueConstraint(
                fields=("product", "fee_date", "transaction_subtype", "calculated"), name="unique_fees"
            ),
        ),
    ]
