using Microsoft.Extensions.Logging;

using DomainResults.Common;

using MongoDB.Bson.Serialization;
using MongoDB.Driver;

using DataProviders.Abstractions;
using Core.DomainObjects.Documents;

namespace DataProviders.Collections {

  public interface IShopCartDataProvider {
    (Guid?, IDomainResult) Insert(ShopCartItem obj);
    (List<ShopCartItem>?, IDomainResult) GetAll(Guid siteId, Guid userId);
    (ShopCartItem?, IDomainResult) Get(Guid siteId, Guid userId, string sku);
    (Guid?, IDomainResult) Update(ShopCartItem shopCart);
    IDomainResult Delete(Guid id);
    IDomainResult DeleteAll(Guid siteId, Guid userId);
  }

  public class ShopCartDataProvider : CollectionDataProviderBase<ShopCartItem>, IShopCartDataProvider {
    private const string _collectionName = "shopcart";

    public ShopCartDataProvider(
      ILogger<CollectionDataProviderBase<ShopCartItem>> logger,
      IMongoClient client,
      IIdGenerator idGenerator,
      ISessionService sessionService) : base(logger, client, idGenerator, sessionService) {
    }

    public (Guid?, IDomainResult) Insert(ShopCartItem obj) =>
      Insert(obj, _collectionName);

    public (List<ShopCartItem>?, IDomainResult) GetAll(Guid siteId, Guid userId) =>
      GetWithPredicate(x => x.SiteId == siteId && x.UserId == userId, 0, 0,_collectionName);

    public (ShopCartItem?, IDomainResult) Get(Guid siteId, Guid userId, string sku) {
      var (list, result) = GetWithPredicate(x => x.SiteId == siteId && x.UserId == userId && x.Sku == sku, 0, 0, _collectionName);

      if (!result.IsSuccess || list == null)
        return (null, result);

      return (list.First(), result);
    }

    public (Guid?, IDomainResult) Update(ShopCartItem shopCart) =>
      UpdateWithPredicate(shopCart, x => x.Id == shopCart.Id, _collectionName);

    public IDomainResult Delete(Guid id) =>
      DeleteWithPredicate(x => x.Id == id, _collectionName);

    public IDomainResult DeleteAll(Guid siteId, Guid userId) =>
      DeleteManyWithPredicate(x => x.SiteId == siteId && x.UserId == userId, _collectionName);
  }
}
