public async Task <GroupedProviderSearchResults> SearchProvidersWithGroupedResults(string apprenticeshipId, string postCode, Pagination pagination, bool hasNonLevyContract, bool showNationalOnly)
        {
            if (string.IsNullOrEmpty(postCode))
            {
                return(new GroupedProviderSearchResults {
                    PostCodeMissing = true
                });
            }

            try
            {
                var coordinateResponse = await _postCodeLookup.GetLatLongFromPostCode(postCode);

                var coordinates = coordinateResponse.Coordinate;


                if (coordinateResponse.ResponseCode != LocationLookupResponse.Ok)
                {
                    return(GetGroupedProviderSearchResultErrorResponse(postCode, coordinateResponse.ResponseCode));
                }

                var takeElements = pagination.Take == 0 ? _paginationSettings.DefaultResultsAmount : pagination.Take;

                LogSearchRequest(postCode, coordinates);

                var filter = new ProviderSearchFilter
                {
                    DeliveryModes      = null,
                    HasNonLevyContract = hasNonLevyContract,
                    ShowNationalOnly   = showNationalOnly
                };

                var searchResults = await _providerSearchProvider.SearchProvidersByLocationGroupByProvider(apprenticeshipId, coordinates, pagination.Page, takeElements, filter);

                var result = new GroupedProviderSearchResults
                {
                    TotalResults              = searchResults.Total,
                    ResultsToTake             = takeElements,
                    PostCode                  = postCode,
                    ShowNationalProvidersOnly = false,
                    Hits                 = searchResults.Hits,
                    LastPage             = takeElements > 0 ? (int)System.Math.Ceiling((double)searchResults.Total / takeElements) : 1,
                    HasNationalProviders = searchResults.HasNationalProviders
                };

                return(result);
            }
            catch (SearchException ex)
            {
                _logger.Error(ex, "Search for provider failed.");

                return(GetGroupedProviderSearchResultErrorResponse(postCode, ServerLookupResponse.InternalServerError));
            }
        }
        private static GroupedProviderSearchResults GetGroupedProviderSearchResultErrorResponse(string postCode, string responseCode)
        {
            var errorResponse = new GroupedProviderSearchResults
            {
                TotalResults = 0,
                PostCode     = postCode,
                Hits         = new GroupedProviderSearchResultItem[0],
                ResponseCode = responseCode
            };

            return(errorResponse);
        }