using Microsoft.Extensions.Logging;

using DomainResults.Common;

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

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

namespace DataProviders.Collections {
  public interface IShopCatalogDataProvider {
    (Guid?, IDomainResult) Insert(ShopItem obj);
    (ShopItem?, IDomainResult) Get(Guid siteId, string sku);
    (ShopItem?, IDomainResult) GetBySlug(Guid siteId, string slug);
    (List<ShopItem>?, IDomainResult) GetBySlugs(Guid siteId, List<string> slugs);
    (List<ShopItem>?, IDomainResult) GetAll(Guid siteId, int skip, int take);
    (Guid?, IDomainResult) Update(ShopItem shopCart);
    IDomainResult Delete(Guid id);
    IDomainResult DeleteAll(Guid siteId);
  }

  public class ShopCatalogDataProvider : CollectionDataProviderBase<ShopItem>, IShopCatalogDataProvider {

    private const string _collectionName = "shopcatalog";

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

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

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

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

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

    public (ShopItem?, IDomainResult) GetBySlug(Guid siteId, string slug) {
      var (list, result) = GetBySlugs(siteId, new List<string> { slug });

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

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

    public (List<ShopItem>?, IDomainResult) GetBySlugs(Guid siteId, List<string> slugs) =>
      GetWithPredicate(x => x.SiteId == siteId && x.L10n.Any(y => slugs.Contains(y.Slug)), _collectionName);

    public (List<ShopItem>?, IDomainResult) GetAll(Guid siteId, int skip, int take) =>
      GetWithPredicate(x => x.SiteId == siteId, skip, take, _collectionName);

    public (Guid?, IDomainResult) Update(ShopItem 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) =>
      DeleteManyWithPredicate(x => x.SiteId == siteId, _collectionName);
  }
}
