# Generated by Django 5.2.13 on 2026-05-07 04:10

from django.db import migrations, models


def add_integer_line_number(apps, schema_editor):
    """Add integer line numbers to existing line items."""

    print("\nUpdating line items to add integer line numbers:")

    for model in [
        apps.get_model('order', 'PurchaseOrderLineItem'),
        apps.get_model('order', 'ReturnOrderLineItem'),
        apps.get_model('order', 'SalesOrderLineItem'),
        apps.get_model('order', 'PurchaseOrderExtraLine'),
        apps.get_model('order', 'ReturnOrderExtraLine'),
        apps.get_model('order', 'SalesOrderExtraLine'),
    ]:
        items = []

        for item in model.objects.exclude(line__isnull=True).exclude(line=''):
            # Attempt to convert the existing line number to an integer
            try:
                item.line_int = int(item.line)
                items.append(item)
            except (ValueError, TypeError):
                pass

        if len(items) > 0:
            print(f"- Updating {len(items)} items for model {model._meta.model_name}")
            model.objects.bulk_update(items, ['line_int'], batch_size=250)



class Migration(migrations.Migration):

    dependencies = [
        ("order", "0116_purchaseorderextraline_line_and_more"),
    ]

    operations = [
        migrations.AddField(
            model_name="purchaseorderextraline",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name="purchaseorderlineitem",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name="returnorderextraline",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name="returnorderlineitem",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name="salesorderextraline",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.AddField(
            model_name="salesorderlineitem",
            name="line_int",
            field=models.IntegerField(default=0),
        ),
        migrations.RunPython(
            code=add_integer_line_number,
            reverse_code=migrations.RunPython.noop,
        ),
    ]
