using FruitBank.Common.Entities;

namespace FruitBank.Common.Helpers;

public static class MeasuringValuesHelper
{
    public static void SetShippingItemTotalMeasuringValues(ShippingItem? shippingItem)
    {
        if (shippingItem == null) return;

        var totalMeasuringValues = GetTotalNetAndGrossWeightFromPallets(shippingItem);

        shippingItem.MeasuredQuantity = totalMeasuringValues.TotalQuantity;
        shippingItem.MeasuredNetWeight = totalMeasuringValues.TotalNetWeight;
        shippingItem.MeasuredGrossWeight = totalMeasuringValues.TotalGrossWeight;
    }

    public static (int TotalQuantity, double TotalNetWeight, double TotalGrossWeight) GetTotalNetAndGrossWeightFromPallets(ShippingItem? shippingItem)
    {
        if (shippingItem?.ShippingItemPallets == null) return (0, 0d, 0d);

        var totalQuantity = 0;
        var totalNetWeight = 0d;
        var totalGrossWeight = 0d;

        foreach (var shippingItemPallet in shippingItem.ShippingItemPallets)
        {
            totalQuantity += shippingItemPallet.TrayQuantity;
            totalNetWeight += shippingItemPallet.NetWeight;
            totalGrossWeight += shippingItemPallet.GrossWeight;
        }

        return (totalQuantity, double.Round(totalNetWeight, 1), Math.Round(totalGrossWeight, 1));
    }
}