# Generated by Django 5.2.10 on 2026-02-05 12:18

from django.db import migrations


def add_part_links(apps, schema_editor):
    """Add links to the Part model for all existing StockItemTracking entries."""

    StockItemTracking = apps.get_model('stock', 'StockItemTracking')

    history_entries = []

    N = StockItemTracking.objects.count()

    if N > 0:
        print(f"\nUpdating {N} StockItemTracking entries with part links...")

    for tracking in StockItemTracking.objects.filter(part__isnull=True).select_related('item__part'):

        item = tracking.item

        # No item link - skip
        if item is None:
            continue

        part = item.part

        # No part link - skip
        if part is None:
            continue

        # Already linked to the correct part - skip
        if tracking.part == part:
            continue

        tracking.part = part
        history_entries.append(tracking)

        # Process in batches to avoid issues with very large datasets
        if len(history_entries) >= 100:
            StockItemTracking.objects.bulk_update(history_entries, ['part'])
            history_entries = []
            print(".", end='', flush=True)

    if len(history_entries) > 0:
        StockItemTracking.objects.bulk_update(history_entries, ['part'])


def remove_null_items(apps, schema_editor):
    """Reverse migration - remove any StockItemTracking entries which have a null item link."""

    StockItemTracking = apps.get_model('stock', 'StockItemTracking')

    null_items = StockItemTracking.objects.filter(item__isnull=True)

    count = null_items.count()

    if count > 0:
        null_items.delete()
        print(f"\nDeleted {count} StockItemTracking entries with null item links")

class Migration(migrations.Migration):

    dependencies = [
        ("stock", "0117_stockitemtracking_part_alter_stockitemtracking_item"),
    ]

    operations = [
        migrations.RunPython(
            add_part_links,
            reverse_code=remove_null_items,
        )
    ]
