from django.db import migrations, models


def backfill_average_prices(apps, schema_editor):
    Stock = apps.get_model("shop_management", "Stock")
    for stock in Stock.objects.select_related("purchase_item").all():
        purchase_item = stock.purchase_item
        if purchase_item:
            stock.average_wholesale_price = purchase_item.wholesale_price
            stock.average_retail_price = purchase_item.retail_price or purchase_item.sale_price
            stock.save(update_fields=["average_wholesale_price", "average_retail_price"])


class Migration(migrations.Migration):

    dependencies = [
        ("shop_management", "0058_stock_average_buy_price"),
    ]

    operations = [
        migrations.AddField(
            model_name="stock",
            name="average_wholesale_price",
            field=models.DecimalField(blank=True, decimal_places=2, help_text="Weighted average wholesale price for the current stock quantity.", max_digits=12, null=True),
        ),
        migrations.AddField(
            model_name="stock",
            name="average_retail_price",
            field=models.DecimalField(blank=True, decimal_places=2, help_text="Weighted average retail price for the current stock quantity.", max_digits=12, null=True),
        ),
        migrations.RunPython(backfill_average_prices, migrations.RunPython.noop),
    ]
