using Microsoft.Extensions.Logging;

using DataProviders.Abstractions;
using DomainObjects.Documents;

using DomainResults.Common;


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


namespace DataProviders.Collections {

  public interface IUserDataProvider {
    (UserDocument?, IDomainResult) Get(Guid userId);

    (UserDocument?, IDomainResult) GetByUsername(string nickName);

    (Guid?, IDomainResult) Update(UserDocument user);
  }

  public class UserDataProvider : CollectionDataProviderBase<UserDocument>, IUserDataProvider {

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

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

    public (UserDocument?, IDomainResult) Get(Guid userId) {
      var (list, result) = GetWithPredicate(x => x.Id == userId);

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

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

    public (UserDocument?, IDomainResult) GetByUsername(string username) {
      var (list, result) = GetWithPredicate(x => x.Username == username);

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

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

    public (Guid?, IDomainResult) Update(UserDocument user) =>
      UpdateWithPredicate(user, x => x.Id == user.Id);

  }
}
