using Bp.Sync.BackEnd.Infrastructure.ElasticDbContext;
using Bp.Sync.Domain.Elastics.Inventories.Categories;
using Bp.Sync.Dto.Results;
using Bp.Sync.Dto.SmartTable;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Bp.Sync.BackEnd.Infrastructure.Repositories
{
    public interface IBaseConfigurationRepository
    {
        Task<BaseResult> Add(BaseConfigurationElastic BaseConfiguration);
        Task<BaseResult> AddManyAsync(IEnumerable<BaseConfigurationElastic> BaseConfigurations);
        Task<SmartTableResult<BaseConfigurationElastic>> Search(BoolQueryDescriptor<BaseConfigurationElastic> query);

    }
    public class BaseConfigurationRepository : IBaseConfigurationRepository
    {
        private readonly ElasticIndex<BaseConfigurationElastic> _dbContext;

        public BaseConfigurationRepository(IOptions<ElasticConnectionSettings> settings)
        {
            _dbContext = new ElasticIndex<BaseConfigurationElastic>(settings.Value.ClusterUrl, "inventorybaseconfiguration");
        }


        public async Task<SmartTableResult<BaseConfigurationElastic>> Search(BoolQueryDescriptor<BaseConfigurationElastic> query)
        {
            return await _dbContext.Search(query);
        }


        public async Task<BaseResult> Add(BaseConfigurationElastic BaseConfiguration)
        {
            var result = new BaseResult() { Result = Dto.Results.Result.Success };
            var rs = await _dbContext.Insert(BaseConfiguration);
            if (rs.IsValid)
            {
                result.Result = Dto.Results.Result.Success;
            }
            else
            {
                result.Result = Dto.Results.Result.SystemError;
                result.Message = "Không tạo được bản ghi";
            }
            return result;
        }
        public async Task<BaseResult> AddManyAsync(IEnumerable<BaseConfigurationElastic> BaseConfigurations)
        {
            var result = new BaseResult { Result = Dto.Results.Result.Success };
            try
            {
                var rs = await _dbContext.InsertMany(BaseConfigurations);
                if (rs.IsValid) return result;
                else
                {
                    result.Result = Dto.Results.Result.Failed;
                    result.Message = rs.Errors.ToString();
                    return result;
                }
            }
            catch (Exception exx)
            {
                result.Result = Dto.Results.Result.Failed;
                result.Message = exx.Message.ToString();
                return result;
            }
        }

    }
}
