# Generated by GitHub Copilot on 2026-01-23

# Standard Library
from decimal import ROUND_CEILING, Decimal

# Django
from django.db import migrations, models
from django.db.models import Sum


def _round_total(value: Decimal) -> Decimal:
    return Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_CEILING)


def populate_rounded_totals(apps, schema_editor):
    BuyOrder = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    BuyItem = apps.get_model("indy_hub", "MaterialExchangeBuyOrderItem")

    for order in BuyOrder.objects.all():
        total = (
            BuyItem.objects.filter(order_id=order.id).aggregate(
                total=Sum("total_price")
            )
        ).get("total")
        if total is None:
            rounded = Decimal("0")
        else:
            rounded = _round_total(total)
        BuyOrder.objects.filter(id=order.id).update(rounded_total_price=rounded)


def reset_rounded_totals(apps, schema_editor):
    BuyOrder = apps.get_model("indy_hub", "MaterialExchangeBuyOrder")
    BuyOrder.objects.update(rounded_total_price=None)


class Migration(migrations.Migration):

    dependencies = [
        ("indy_hub", "0072_notification_webhooks"),
    ]

    operations = [
        migrations.AddField(
            model_name="materialexchangebuyorder",
            name="rounded_total_price",
            field=models.DecimalField(
                blank=True,
                decimal_places=0,
                help_text="Rounded total price for contract (ceil to whole ISK)",
                max_digits=20,
                null=True,
            ),
        ),
        migrations.RunPython(populate_rounded_totals, reset_rounded_totals),
    ]
