using Bp.Sync.BackEnd.Infrastructure.ElasticDbContext;
using Bp.Sync.Domain.Elastics.Inventories;
using Bp.Sync.Domain.Elastics.Inventories.Orders;
using Bp.Sync.Dto.Models;
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 IProductOrderRepository
    {
        Task<BaseResult> Add(ProductOrderElastic ProductOrder);
        Task<BaseResult> AddManyAsync(IEnumerable<ProductOrderElastic> ProductOrders);
        Task<SmartTableResult<ProductOrderElastic>> Search(BoolQueryDescriptor<ProductOrderElastic> query);
        Task<SmartTableResult<BaseLong>> Search(BoolQueryDescriptor<ProductOrderElastic> query, int count);

    }
    public class ProductOrderRepository : IProductOrderRepository
    {
        private readonly ElasticIndex<ProductOrderElastic> _dbContext;

        public ProductOrderRepository(IOptions<ElasticConnectionSettings> settings)
        {
            _dbContext = new ElasticIndex<ProductOrderElastic>(settings.Value.ClusterUrl, "inventoryproductorder");
        }


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


        public async Task<BaseResult> Add(ProductOrderElastic ProductOrder)
        {
            var result = new BaseResult() { Result = Dto.Results.Result.Success };
            var rs = await _dbContext.Insert(ProductOrder);
            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<ProductOrderElastic> ProductOrders)
        {
            var result = new BaseResult { Result = Dto.Results.Result.Success };
            try
            {
                var rs = await _dbContext.InsertMany(ProductOrders);
                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;
            }
        }

        public async Task<SmartTableResult<BaseLong>> Search(BoolQueryDescriptor<ProductOrderElastic> query, int count)
        {
            return await _dbContext.SearchIds(query,count);
        }
    }
}
