using DomainResults.Common;

using DataProviders.Collections;

using Core.Abstractions;

using WeatherForecast.Models.Responses;
using DomainObjects.Documents;
using DomainObjects.Enumerations;

namespace WeatherForecast.Services {

  /// <summary>
  /// 
  /// </summary>
  public interface IShopCartItemsService {

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cartItems"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    (List<ShopCartItemResponseModel>?, IDomainResult) Get(List<ShopCartDocument> cartItems, string? locale);
  }

  /// <summary>
  /// 
  /// </summary>
  public class ShopCartItemsService : ServiceBase<ShopCartItemsService>, IShopCartItemsService {

    private readonly IShopCatalogDataProvider _shopCatalogDataProvider;
    private readonly IShopCartDataProvider _shopCartDataProvider;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="shopCatalogDataProvider"></param>
    /// <param name="shopCartDataprovider"></param>
    public ShopCartItemsService(
      ILogger<ShopCartItemsService> logger,
      IShopCatalogDataProvider shopCatalogDataProvider,
      IShopCartDataProvider shopCartDataprovider
    ) : base(logger) {
      _shopCatalogDataProvider = shopCatalogDataProvider;
      _shopCartDataProvider = shopCartDataprovider;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cartItems"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    public (List<ShopCartItemResponseModel>?, IDomainResult) Get(List<ShopCartDocument> cartItems, string? locale) {
      
      var items = new List<ShopCartItemResponseModel>();
      foreach (var cartItem in cartItems) {
        var (item, result) = _shopCatalogDataProvider.Get(cartItem.Id, cartItem.Sku);
        if (!result.IsSuccess || item == null) {
          var delteResult = _shopCartDataProvider.Delete(cartItem.Id);
          if (!delteResult.IsSuccess)
            return (null, delteResult);
        }
        else
          items.Add(new ShopCartItemResponseModel(item, cartItem, Enumeration.FromDisplayName<Locales>(locale ?? "en-US")));
      }

      return items.Count > 0
        ? IDomainResult.Success(items)
        : IDomainResult.NotFound<List<ShopCartItemResponseModel>?>();
    }
  }
}
