namespace Fast.Web.Logic.GasControl
{
    public class GasControlHelper
    {
        public static int? GetTransferSupplyCounterpartyID(MyDbContext db, int StartTransferDealID, DateOnly GasDay)
        {
            int? TransferSupplyCounterpartyID = null;

            int NextTransferDealID = StartTransferDealID;
            bool SupplyIsTransfer = true;
            while (SupplyIsTransfer)
            {
                var Sup = (
                    from ms in db.GasMarketSupplies
                        .Include(x => x.SupplyNom)
                        .ThenInclude(x => x.Deal)
                    where ms.MarketNom.TransferDealId == NextTransferDealID && ms.Date == GasDay
                    select ms.SupplyNom
                ).FirstOrDefault();

                if (Sup != null)
                {
                    if (Sup.DealId != null)
                    {
                        TransferSupplyCounterpartyID = Sup.Deal?.CounterpartyId;
                        SupplyIsTransfer = false;
                    }
                    else
                    {
                        NextTransferDealID = Sup.TransferDealId.GetValueOrDefault();
                        SupplyIsTransfer = true;
                    }
                }
                else
                    SupplyIsTransfer = false;
            }

            return TransferSupplyCounterpartyID;
        }

    }
}
