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(p => p.PartnerDepots)
                .LoadWith(p => p.ShippingDocuments).ThenLoad(sd => sd.Shipping)
                .LoadWith(p => p.ShippingDocuments).ThenLoad(sd => sd.ShippingItems).ThenLoad(si => si.ShippingItemPallets)
                .LoadWith(p => p.ShippingDocuments).ThenLoad(sd => sd.ShippingDocumentToFiles).ThenLoad(sdtof => sdtof.ShippingDocumentFile)
            : GetAll();
    }

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