using FruitBank.Common.Dtos;
using FruitBank.Common.Entities;
using LinqToDB;
using Mango.Nop.Core.Loggers;
using Mango.Nop.Data.Repositories;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Events;
using Nop.Data;
using System.Linq;

namespace Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;

public class OrderDtoDbTable : MgDtoDbTableBase<OrderDto, Order>
{
    public OrderDtoDbTable(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings)
        : base(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings)
    {
    }

    public IQueryable<OrderDto> GetAll(bool loadRelations)
    {
        if (loadRelations)
        {
            return GetAll()
                .LoadWith(o => o.GenericAttributes)
                .LoadWith(o => o.Customer)
                .LoadWith(o => o.OrderNotes)
                .LoadWith(o => o.OrderItemDtos).ThenLoad(oi => oi.ProductDto).ThenLoad(prod => prod.GenericAttributes)
                .LoadWith(o => o.OrderItemDtos).ThenLoad(oi => oi.GenericAttributes)
                .LoadWith(o => o.OrderItemDtos).ThenLoad(oi => oi.OrderItemPallets);
        }

        return GetAll().LoadWith(o => o.GenericAttributes);
    }

    public Task<OrderDto> GetByIdAsync(int orderId, bool loadRelations) => GetAll(loadRelations).Where(x => x.Id == orderId).FirstOrDefaultAsync(null);

    public IQueryable<OrderDto> GetAllByOrderStatus(OrderStatus orderStatus, bool loadRelations = true)
        => GetAll(loadRelations).Where(o => o.OrderStatusId == (int)orderStatus);

    public IQueryable<OrderDto> GetAllForMeasuring(DateTime fromDate, bool loadRelations = true)
        => GetAll(loadRelations).Where(o => o.PaymentStatusId < (int)PaymentStatus.Paid
                                            && o.OrderStatusId != (int)OrderStatus.Cancelled
                                            && o.GenericAttributes.Any(ga => ga.Key == nameof(OrderDto.DateOfReceipt) && DateTime.Parse(ga.Value) >= fromDate.Date));
    
    public IQueryable<OrderDto> GetAllByProductId(int productId, bool loadRelations = true) 
        => GetAll(loadRelations).Where(o => o.OrderItemDtos.Any(oi => oi.ProductId == productId));

    public IQueryable<OrderDto> GetAllByProductIds(IEnumerable<int> productIds, bool loadRelations = true)
        => GetAll(loadRelations).Where(o => o.OrderItemDtos.Any(oi => productIds.Contains(oi.ProductId)));

    public IQueryable<OrderDto> GetAllByIds(IEnumerable<int> orderIds, bool loadRelations = true) => GetAll(loadRelations).Where(o => orderIds.Contains(o.Id));
}
