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 IBlogCatalogDataProvider {
    (Guid?, IDomainResult) Insert(BlogItem blogItem);
    (BlogItem?, IDomainResult) Get(Guid siteId, Guid blogId);
    (BlogItem?, IDomainResult) GetBySlug(Guid siteId, string slug);
    (List<BlogItem>?, IDomainResult) GetBySlugs(Guid siteId, List<string> slugs);
    (List<BlogItem>?, IDomainResult) GetAll(Guid siteId, int skip, int take);
    (Guid?, IDomainResult) Update(BlogItem blogItem);
    IDomainResult Delete(Guid id);
    IDomainResult DeleteAll(Guid siteId);
  }

  public class BlogCatalogDataProvider : CollectionDataProviderBase<BlogItem>, IBlogCatalogDataProvider {

    private const string _collectionName = "blogcatalog";

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

    public (Guid?, IDomainResult) Insert(BlogItem blogItem) =>
      Insert(blogItem, _collectionName);

    public (BlogItem?, IDomainResult) Get(Guid siteId, Guid blogId) {
      var (list, result) = GetWithPredicate(x => x.SiteId == siteId && x.Id == blogId, _collectionName);

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

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

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

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

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

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

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