# Generated by Django 3.2.18 on 2023-03-04 09:04

import logging

from django.db import migrations

from djmoney.contrib.exchange.exceptions import MissingRate
from djmoney.contrib.exchange.models import convert_money
from djmoney.money import Money

from common.currency import currency_code_default


logger = logging.getLogger('inventree')


def update_purchase_order_price(apps, schema_editor):
    """Calculate 'total_price' field for each PurchaseOrder"""

    PurchaseOrder = apps.get_model('order', 'purchaseorder')

    currency = currency_code_default()

    valid_count = 0
    invalid_count = 0

    for order in PurchaseOrder.objects.all():

        valid = True

        total_price = Money(0, currency)

        for line in order.lines.all():
            if line.purchase_price:
                try:
                    total_price += convert_money(line.purchase_price, currency) * line.quantity
                except MissingRate:
                    valid = False
                    break

        for line in order.extra_lines.all():
            if line.price:
                try:
                    total_price += convert_money(line.price, currency) * line.quantity
                except MissingRate:
                    valid = False
                    break

        if valid:
            order.total_price = total_price
            order.save()

            valid_count += 1
        else:
            invalid_count +=1

    if valid_count > 0:
        logger.info(f"Updated 'total_price' field for {valid_count} PurchaseOrder instances")

    if invalid_count > 0:
        logger.info(f"'total_price' field could not be updated for {invalid_count} PurchaseOrder instances")


def update_sales_order_price(apps, schema_editor):
    """Calculate 'total_price' field for each SalesOrder"""

    SalesOrder = apps.get_model('order', 'salesorder')

    currency = currency_code_default()

    valid_count = 0
    invalid_count = 0

    for order in SalesOrder.objects.all():

        valid = True

        total_price = Money(0, currency)

        for line in order.lines.all():
            if line.sale_price:
                try:
                    total_price += convert_money(line.sale_price, currency) * line.quantity
                except MissingRate:
                    valid = False
                    break

        for line in order.extra_lines.all():
            if line.price:
                try:
                    total_price += convert_money(line.price, currency) * line.quantity
                except MissingRate:
                    valid = False
                    break

        if valid:
            order.total_price = total_price
            order.save()

            valid_count += 1
        else:
            invalid_count +=1

    if valid_count > 0:
        logger.info(f"Updated 'total_price' field for {valid_count} SalesOrder instances")

    if invalid_count > 0:
        logger.info(f"'total_price' field could not be updated for {invalid_count} SalesOrder instances")


class Migration(migrations.Migration):

    dependencies = [
        ('order', '0078_auto_20230304_0721'),
    ]

    operations = [
        migrations.RunPython(
            update_purchase_order_price,
            reverse_code=migrations.RunPython.noop
        ),
        migrations.RunPython(
            update_sales_order_price,
            reverse_code=migrations.RunPython.noop,
        )
    ]
