using Bp.Sync.BackEnd.Infrastructure.ElasticDbContext;
using Bp.Sync.Domain.Elastics.Inventories;
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 IInvoiceRepository
    {
        Task<BaseResult> Add(InvoiceElastic Invoice);
        Task<BaseResult> AddManyAsync(IEnumerable<InvoiceElastic> Invoices);
        Task<SmartTableResult<InvoiceElastic>> Search(BoolQueryDescriptor<InvoiceElastic> query);
        Task<SmartTableResult<InvoiceElastic>> GetByIds(List<long> ids);

    }
    public class InvoiceRepository : IInvoiceRepository
    {
        private readonly ElasticIndex<InvoiceElastic> _dbContext;

        public InvoiceRepository(IOptions<ElasticConnectionSettings> settings)
        {
            _dbContext = new ElasticIndex<InvoiceElastic>(settings.Value.ClusterUrl, "inventoryinvoice");
        }


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


        public async Task<BaseResult> Add(InvoiceElastic Invoice)
        {
            var result = new BaseResult() { Result = Dto.Results.Result.Success };
            var rs = await _dbContext.Insert(Invoice);
            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<InvoiceElastic> Invoices)
        {
            var result = new BaseResult { Result = Dto.Results.Result.Success };
            try
            {
                var rs = await _dbContext.InsertMany(Invoices);
                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<InvoiceElastic>> GetByIds(List<long> ids)
        {
            var query = new BoolQueryDescriptor<InvoiceElastic>();
            var idsQ = new QueryContainerDescriptor<InvoiceElastic>();
            idsQ.Terms(t => t.Field(f => f.Id).Terms(ids));
            query.Filter(fl => idsQ);
            return await _dbContext.Search(query);
        }
    }
}
