/// <summary> /// Delete a food item from the database. /// Updates the total calories for the diary entry the food item belongs to. /// </summary> /// <param name="id"></param> /// <returns> /// Unsuccessful FoodItemResponse if the food item does not exist; /// Unsuccessful FoodItemResponse if there was an issue removing the food item from the database; /// Successful FoodItemResponse with the food item /// </returns> public async Task <FoodItemResponse> DeleteFoodItemAsync(int id) { // check if the food item exists var existingFoodItem = await _foodItemRepository.GetAsync(id); if (existingFoodItem == null) { return(new FoodItemResponse($"Food item {id} not found")); } var diaryEntry = existingFoodItem.DiaryEntry; // remove the calories from the total calories diaryEntry.TotalCalories -= existingFoodItem.Calories; // check if this food item is the last one in the diary entry var foodItems = existingFoodItem.DiaryEntry.FoodItems; bool deleteDiaryEntry = false; if (foodItems.Count == 1 && foodItems[0].Id == existingFoodItem.Id) { deleteDiaryEntry = true; // mark the diary entry for deletion } // remove the food item from the database and save the changes to the diary entry try { _foodItemRepository.Remove(existingFoodItem); await _unitOfWork.CompleteAsync(); } catch (Exception e) { return(new FoodItemResponse($"An error occurred when deleting diary entry {id}: {e}")); } // wait until after the food item is deleted, as the food item is a child of the diary if (deleteDiaryEntry) { var deleteResult = await _diaryEntryService.DeleteDiaryEntryAsync(diaryEntry.Id); if (!deleteResult.Success) { return(new FoodItemResponse($"Failed to delete diary entry: {deleteResult}")); } } return(new FoodItemResponse(existingFoodItem)); }