using static Managing.Common.Enums;

namespace Managing.Domain.Trades;

public static class OrderBookExtensions
{
    public static decimal GetBestPrice(this Orderbook orderbook, TradeDirection direction, decimal quantity)
    {
        var entries = direction == TradeDirection.Long ? orderbook.Asks : orderbook.Bids;
        var spend = 0m;
        var entryIndex = 0;
        var matches = new List<(decimal amount, decimal price, decimal sum)>();

        while (spend < quantity)
        {
            if (entries[entryIndex].Quantity > quantity - spend)
            {
                var amount = quantity - spend;
                matches.Add((amount, entries[entryIndex].Price, amount * entries[entryIndex].Price));
                spend += amount;
            }
            else
            {
                matches.Add((entries[entryIndex].Quantity, entries[entryIndex].Price, entries[entryIndex].Quantity * entries[entryIndex].Price));
                spend += entries[entryIndex].Quantity;
            }

            entryIndex++;
        }

        var meanPrice = matches.Sum(s => s.sum) / matches.Sum(s => s.amount);

        return meanPrice;
    }
}
