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 PartnerDbTable : MgDbTableBase<Partner>
{
    public PartnerDbTable(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings)
        : base(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings)
    {
    }

    public override IOrderedQueryable<Partner> GetAll()
        => base.GetAll().OrderBy(p => p.Name);

    public IQueryable<Partner> GetAll(bool loadRelations)
    {
        return loadRelations
            ? GetAll()
                .LoadWith(sd => sd.ShippingDocuments).ThenLoad(s => s.Shipping)
                .LoadWith(sd => sd.ShippingDocuments).ThenLoad(si => si.ShippingItems).ThenLoad(sip => sip.ShippingItemPallets)
                .LoadWith(sd => sd.ShippingDocuments).ThenLoad(sdtof => sdtof.ShippingDocumentToFiles).ThenLoad(f => f.ShippingDocumentFile)
            : GetAll();
    }

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


    public Task<Partner> GetByIdNameAsync(string name, bool loadRelations)
        => GetAll(loadRelations).FirstOrDefaultAsync(p => p.Name == name);
}