# Generated by Django 3.2.6 on 2021-09-13 07:31

from django.db import migrations

from ...order import FulfillmentStatus


def increase_order_lines_quantity_for_waiting_fulfillments(apps, schema):
    """Increase order_line quantity fulfilled.

    Add quantity of each related fulfillment line
    which fulfillment is in WAITING_FOR_APPROVAL state.
    """
    FulfillmentLine = apps.get_model("order", "FulfillmentLine")
    for fulfillment_line in FulfillmentLine.objects.filter(
        fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL
    ).iterator():
        order_line = fulfillment_line.order_line
        order_line.quantity_fulfilled += fulfillment_line.quantity
        if order_line.quantity_fulfilled > order_line.quantity:
            order_line.quantity_fulfilled = order_line.quantity
        order_line.save(update_fields=["quantity_fulfilled"])


def decrease_order_lines_quantity_for_waiting_fulfillments(apps, schema):
    FulfillmentLine = apps.get_model("order", "FulfillmentLine")
    for fulfillment_line in FulfillmentLine.objects.filter(
        fulfillment__status=FulfillmentStatus.WAITING_FOR_APPROVAL
    ).iterator():
        order_line = fulfillment_line.order_line
        order_line.quantity_fulfilled -= fulfillment_line.quantity
        if order_line.quantity_fulfilled < 0:
            order_line.quantity_fulfilled = 0
        order_line.save(update_fields=["quantity_fulfilled"])


class Migration(migrations.Migration):

    dependencies = [
        ("order", "0117_merge_20210903_1013"),
    ]

    operations = [
        migrations.RunPython(
            increase_order_lines_quantity_for_waiting_fulfillments,
            reverse_code=decrease_order_lines_quantity_for_waiting_fulfillments,
        ),
    ]
