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

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

public class OrderItemDtoDbTable : MgDtoDbTableBase<OrderItemDto, OrderItem>
{
    public OrderItemDtoDbTable(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings)
        : base(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings)
    {
    }

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

    public Task<OrderItemDto> GetByIdAsync(int orderItemId, bool loadRelations) => GetAll(loadRelations).Where(oi => oi.Id == orderItemId).FirstOrDefaultAsync(null);

    public IQueryable<OrderItemDto> GetAllByOrderId(int orderId, bool loadRelations = true) => GetAll(loadRelations).Where(oi => oi.OrderId == orderId);
    
    public IQueryable<OrderItemDto> GetAllByProductId(int productId, bool loadRelations = true) => GetAll(loadRelations).Where(oi => oi.ProductId == productId);

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

    public IQueryable<OrderItemDto> GetAllByIds(IEnumerable<int> orderItemIds, bool loadRelations = true) => GetAll(loadRelations).Where(oi => orderItemIds.Contains(oi.Id));
    public IQueryable<OrderItemDto> GetAllByOrderIds(IEnumerable<int> orderIds, bool loadRelations = true) => GetAll(loadRelations).Where(oi => orderIds.Contains(oi.OrderId));
}