public async Task <IActionResult> ManagerClaimGame([FromBody] ClaimGameRequest request)
    {
        var leagueYearPublisherRecord = await GetExistingLeagueYearAndPublisher(request.PublisherID, ActionProcessingModeBehavior.Ban, RequiredRelationship.LeagueManager, RequiredYearStatus.YearNotFinishedDraftFinished);

        if (leagueYearPublisherRecord.FailedResult is not null)
        {
            return(leagueYearPublisherRecord.FailedResult);
        }
        var validResult = leagueYearPublisherRecord.ValidResult !;
        var leagueYear  = validResult.LeagueYear;
        var publisher   = validResult.Publisher;

        MasterGame?masterGame = null;

        if (request.MasterGameID.HasValue)
        {
            masterGame = await _interLeagueService.GetMasterGame(request.MasterGameID.Value);
        }

        bool counterPickedGameIsManualWillNotRelease = PlayerGameExtensions.CounterPickedGameIsManualWillNotRelease(leagueYear, request.CounterPick, masterGame, false);
        ClaimGameDomainRequest domainRequest         = new ClaimGameDomainRequest(leagueYear, publisher, request.GameName, request.CounterPick, counterPickedGameIsManualWillNotRelease, request.ManagerOverride, false, masterGame, null, null);
        ClaimResult            result = await _gameAcquisitionService.ClaimGame(domainRequest, true, false, false);

        var viewModel = new ManagerClaimResultViewModel(result);

        await _fantasyCriticService.UpdatePublisherGameCalculatedStats(leagueYear);

        return(Ok(viewModel));
    }
    private ProcessedBidSet ProcessPickupsForLeagueYear(LeagueYear leagueYear, IReadOnlyList <PickupBid> activeBidsForLeague,
                                                        PublisherStateSet publisherStateSet, SystemWideValues systemWideValues, Instant processingTime)
    {
        LeagueYear       updatedLeagueYear = publisherStateSet.GetUpdatedLeagueYear(leagueYear);
        var              gamesGroupedByPublisherAndGame = activeBidsForLeague.GroupBy(x => (x.Publisher.PublisherID, x.MasterGame.MasterGameID));
        var              duplicateBidGroups             = gamesGroupedByPublisherAndGame.Where(x => x.Count() > 1).ToList();
        List <PickupBid> duplicateBids = new List <PickupBid>();

        foreach (var duplicateBidGroup in duplicateBidGroups)
        {
            var bestBid   = duplicateBidGroup.WhereMax(x => x.BidAmount).WhereMin(x => x.Timestamp).First();
            var otherBids = duplicateBidGroup.Except(new List <PickupBid>()
            {
                bestBid
            });
            duplicateBids.AddRange(otherBids);
        }

        var nonDuplicateBids = activeBidsForLeague.Except(duplicateBids);

        List <PickupBid> noSpaceLeftBids       = new List <PickupBid>();
        List <PickupBid> insufficientFundsBids = new List <PickupBid>();
        List <PickupBid> belowMinimumBids      = new List <PickupBid>();
        List <KeyValuePair <PickupBid, string> > invalidGameBids = new List <KeyValuePair <PickupBid, string> >();

        var currentDate = processingTime.ToEasternDate();

        List <ValidPickupBid> validPickupBids = new List <ValidPickupBid>();

        foreach (var activeBid in nonDuplicateBids)
        {
            Publisher bidPublisher = publisherStateSet.GetPublisher(activeBid.Publisher.PublisherID);
            bool      counterPickedGameIsManualWillNotRelease = PlayerGameExtensions.CounterPickedGameIsManualWillNotRelease(updatedLeagueYear, activeBid.CounterPick, activeBid.MasterGame, true);
            var       gameRequest = new ClaimGameDomainRequest(updatedLeagueYear, bidPublisher, activeBid.MasterGame.GameName, activeBid.CounterPick, counterPickedGameIsManualWillNotRelease, false, false, activeBid.MasterGame, null, null);

            PickupBid pickupBidWithConditionalDropResult = activeBid;
            int?      validConditionalDropSlot           = null;
            if (activeBid.ConditionalDropPublisherGame is not null)
            {
                var conditionalDropResult = _gameAcquisitionService.CanConditionallyDropGame(activeBid, updatedLeagueYear, bidPublisher, processingTime);
                pickupBidWithConditionalDropResult = activeBid.WithConditionalDropResult(conditionalDropResult);
                if (conditionalDropResult.Result.IsSuccess)
                {
                    validConditionalDropSlot = activeBid.ConditionalDropPublisherGame.SlotNumber;
                }
            }

            var claimResult = _gameAcquisitionService.CanClaimGame(gameRequest, null, validConditionalDropSlot, true, false);
            if (claimResult.NoSpaceError)
            {
                noSpaceLeftBids.Add(pickupBidWithConditionalDropResult);
                continue;
            }

            if (!claimResult.Success)
            {
                invalidGameBids.Add(new KeyValuePair <PickupBid, string>(pickupBidWithConditionalDropResult, string.Join(" AND ", claimResult.Errors.Select(x => x.Error))));
                continue;
            }

            if (pickupBidWithConditionalDropResult.BidAmount > bidPublisher.Budget)
            {
                insufficientFundsBids.Add(pickupBidWithConditionalDropResult);
                continue;
            }

            if (pickupBidWithConditionalDropResult.BidAmount < updatedLeagueYear.Options.MinimumBidAmount)
            {
                belowMinimumBids.Add(pickupBidWithConditionalDropResult);
                continue;
            }

            validPickupBids.Add(new ValidPickupBid(pickupBidWithConditionalDropResult, claimResult.BestSlotNumber !.Value));
        }

        var winnableBids = GetWinnableBids(updatedLeagueYear, validPickupBids, systemWideValues, currentDate);
        var winningBids  = GetWinningBids(winnableBids);

        var takenGames = winningBids.Select(x => x.PickupBid.MasterGame);
        var losingBids = activeBidsForLeague
                         .Except(winningBids.Select(x => x.PickupBid))
                         .Except(duplicateBids)
                         .Except(noSpaceLeftBids)
                         .Except(insufficientFundsBids)
                         .Except(belowMinimumBids)
                         .Except(invalidGameBids.Select(x => x.Key))
                         .Where(x => takenGames.Contains(x.MasterGame))
                         .Select(x => new FailedPickupBid(x, "Publisher was outbid.", systemWideValues, currentDate));

        var duplicateBidFailures         = duplicateBids.Select(x => new FailedPickupBid(x, "You cannot have multiple bids for the same game. This bid has been ignored.", systemWideValues, currentDate));
        var invalidGameBidFailures       = invalidGameBids.Select(x => new FailedPickupBid(x.Key, "Game is no longer eligible: " + x.Value, systemWideValues, currentDate));
        var insufficientFundsBidFailures = insufficientFundsBids.Select(x => new FailedPickupBid(x, "Not enough budget.", systemWideValues, currentDate));
        var belowMinimumBidFailures      = belowMinimumBids.Select(x => new FailedPickupBid(x, "Bid is below the minimum bid amount.", systemWideValues, currentDate));
        List <FailedPickupBid> noSpaceLeftBidFailures = new List <FailedPickupBid>();

        foreach (var noSpaceLeftBid in noSpaceLeftBids)
        {
            FailedPickupBid failedBid;
            if (noSpaceLeftBid.ConditionalDropPublisherGame is not null && noSpaceLeftBid.ConditionalDropResult !.Result.IsFailure)
            {
                failedBid = new FailedPickupBid(noSpaceLeftBid, "No roster spots available. Attempted to conditionally drop game: " +
                                                $"{noSpaceLeftBid.ConditionalDropPublisherGame.MasterGame!.MasterGame.GameName} " +
                                                $"but failed because: {noSpaceLeftBid.ConditionalDropResult.Result.Error}", systemWideValues, currentDate);
            }
    public async Task <IActionResult> ManagerDraftGame([FromBody] ManagerDraftGameRequest request)
    {
        var leagueYearPublisherRecord = await GetExistingLeagueYearAndPublisher(request.PublisherID, ActionProcessingModeBehavior.Allow, RequiredRelationship.LeagueManager, RequiredYearStatus.ActiveDraft);

        if (leagueYearPublisherRecord.FailedResult is not null)
        {
            return(leagueYearPublisherRecord.FailedResult);
        }
        var validResult = leagueYearPublisherRecord.ValidResult !;
        var leagueYear  = validResult.LeagueYear;
        var publisher   = validResult.Publisher;

        var nextPublisher = _draftService.GetNextDraftPublisher(leagueYear);

        if (nextPublisher is null)
        {
            return(BadRequest("There are no spots open to draft."));
        }

        if (!nextPublisher.Equals(publisher))
        {
            return(BadRequest("That publisher is not next up for drafting."));
        }

        MasterGame?masterGame = null;

        if (request.MasterGameID.HasValue)
        {
            masterGame = await _interLeagueService.GetMasterGame(request.MasterGameID.Value);
        }

        var draftPhase = _draftService.GetDraftPhase(leagueYear);

        if (draftPhase.Equals(DraftPhase.StandardGames))
        {
            if (request.CounterPick)
            {
                return(BadRequest("Not drafting counterPicks now."));
            }
        }

        if (draftPhase.Equals(DraftPhase.CounterPicks))
        {
            if (!request.CounterPick)
            {
                return(BadRequest("Not drafting standard games now."));
            }
        }

        var  draftStatus = _draftService.GetDraftStatus(draftPhase, leagueYear);
        bool counterPickedGameIsManualWillNotRelease = PlayerGameExtensions.CounterPickedGameIsManualWillNotRelease(leagueYear, request.CounterPick, masterGame, false);
        ClaimGameDomainRequest domainRequest         = new ClaimGameDomainRequest(leagueYear, publisher, request.GameName, request.CounterPick, counterPickedGameIsManualWillNotRelease, request.ManagerOverride, false,
                                                                                  masterGame, draftStatus.DraftPosition, draftStatus.OverallDraftPosition);

        var result = await _draftService.DraftGame(domainRequest, true);

        var viewModel = new ManagerClaimResultViewModel(result.Result);
        await _hubContext.Clients.Group(leagueYear.GetGroupName).SendAsync("RefreshLeagueYear");

        if (result.DraftComplete)
        {
            await _hubContext.Clients.Group(leagueYear.GetGroupName).SendAsync("DraftFinished");
        }

        return(Ok(viewModel));
    }