# Generated by Django 4.1.5 on 2023-07-21 18:17
from django.db.models import Count
from django.db import migrations


def purge_duplicate_named(apps, schema_editor):
    for model_name in ("Category", "Manufacturer", "Unit", "Vendor"):
        field_name = model_name.lower()
        model = apps.get_model("inventory", model_name)
        duplicates = (
            model.objects.values("name").annotate(count=Count("id")).filter(count__gt=1)
        )
        for duplicate in duplicates:
            print(
                f"found {duplicate['count']} duplicates for {model_name} with name {duplicate['name']}"
            )
            keep, *destroy = model.objects.filter(name=duplicate["name"])
            for object in destroy:
                for item in object.item_set.all():
                    print(
                        f"{item}: reassigned {field_name} from {getattr(item, field_name)} to {keep}"
                    )
                    setattr(item, field_name, keep)
                    item.save()
                if object.item_set.count() == 0:
                    print(f"{object}: no more associated records; deleting")
                    object.delete()


def purge_duplicate_catalog(apps, schema_editor):
    Item = apps.get_model("inventory", "Item")
    duplicates = (
        Item.objects.values("vendor", "catalog")
        .annotate(count=Count("id"))
        .filter(count__gt=1)
    )
    for duplicate in duplicates:
        print(
            f"found {duplicate['count']} duplicates for Item with catalog {duplicate['catalog']} for vendor {duplicate['vendor']}"
        )
        keep, *destroy = Item.objects.filter(
            vendor=duplicate["vendor"], catalog=duplicate["catalog"]
        )
        for object in destroy:
            for orderitem in object.orderitem_set.all():
                print(f"{orderitem}: reassigned item from {orderitem.item} to {keep}")
                orderitem.item = keep
                orderitem.save()
            if object.item_set.count() == 0:
                print(f"{object}: no more associated records; deleting")
                object.delete()


class Migration(migrations.Migration):
    dependencies = [
        ("inventory", "0006_rename_ptao_order_account"),
    ]

    operations = [
        migrations.RunPython(purge_duplicate_named),
        migrations.RunPython(purge_duplicate_catalog),
    ]
