using Microsoft.Extensions.Logging;

using DomainResults.Common;

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

using DataProviders.Abstractions;
using DomainObjects.Documents;

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

  public class ShopCatalogDataProvider : CollectionDataProviderBase<ShopDocument>, IShopCatalogDataProvider {

    private const string _databaseName = "reactredux";
    private const string _collectionName = "shopcatalog";

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

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

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

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

    public (ShopDocument?, 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<ShopDocument>?, IDomainResult) GetBySlugs(Guid siteId, List<string> slugs) =>
      GetWithPredicate(x => x.SiteId == siteId && x.L10n.Any(y => slugs.Contains(y.Slug)));

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

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

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

    public IDomainResult DeleteAll(Guid siteId) =>
      DeleteManyWithPredicate(x => x.SiteId == siteId);
  }
}
