using FruitBank.Common.Entities;
using LinqToDB;
using Mango.Nop.Data.Repositories;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Events;
using Nop.Data;
using Mango.Nop.Core.Loggers;

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

public class ShippingDocumentDbTable : MgDbTableBase<ShippingDocument>
{
    public ShippingDocumentDbTable(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings)
        : base(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings)
    {
    }

    public override IOrderedQueryable<ShippingDocument> GetAll()
        => base.GetAll().OrderBy(sd => sd.ShippingDate);

    public IQueryable<ShippingDocument> GetAll(bool loadRelations)
    {
        return loadRelations
            ? GetAll()
                .LoadWith(sd => sd.Shipping)
                .LoadWith(sd => sd.Shipping).ThenLoad(s => s.CargoPartner)
                .LoadWith(sd => sd.Shipping).ThenLoad(s => s.CargoTruck)
                .LoadWith(sd => sd.Shipping).ThenLoad(s => s.CargoTrailer)
                .LoadWith(sd => sd.ShippingItems).ThenLoad(si => si.Pallet)
                .LoadWith(sd => sd.ShippingItems).ThenLoad(si => si.ProductDto).ThenLoad(prod => prod.GenericAttributes)
                .LoadWith(sd => sd.ShippingItems).ThenLoad(si => si.ShippingItemPallets)
                .LoadWith(sd => sd.ShippingDocumentToFiles).ThenLoad(sdtof => sdtof.ShippingDocumentFile)
                .LoadWith(sd => sd.Partner)
            : GetAll();
    }

    public IQueryable<ShippingDocument> GetAllNotMeasured(bool loadRelations)
        => GetAll(loadRelations).Where(sd => !sd.IsAllMeasured);


    public Task<ShippingDocument> GetByIdAsync(int id, bool loadRelations)
        => GetAll(loadRelations).FirstOrDefaultAsync(sd => sd.Id == id);

    public IQueryable<ShippingDocument> GetAllByShippingIdAsync(int shippingId, bool loadRelations)
        => GetAll(loadRelations).Where(sd => sd.ShippingId == shippingId);

    public IQueryable<ShippingDocument> GetAllByProductIdAsync(int productId, bool loadRelations)
        => GetAll(loadRelations).Where(sd => sd.ShippingItems.Any(si => si.ProductId == productId));

    public IQueryable<ShippingDocument> GetAllByPartnerIdAsync(int partnerId, bool loadRelations)
        => GetAll(loadRelations).Where(sd => sd.PartnerId == partnerId);


}