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

    public override IOrderedQueryable<Shipping> GetAll()
        => base.GetAll().OrderBy(s => s.ShippingDate);

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

    public IQueryable<Shipping> GetAllNotMeasured(bool loadRelations, int lastDaysCount)
        => GetAll(loadRelations).Where(s => !s.IsAllMeasured || s.MeasuredDate == null || s.MeasuredDate >= DateTime.Now.AddDays(-lastDaysCount));


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

    protected override void OnUpdate(Shipping entity)
    {
        if (entity is { IsAllMeasured: true, MeasuredDate: null }) entity.MeasuredDate = DateTime.Now;

        base.OnUpdate(entity);
    }    
}