using FruitBank.Common.Interfaces;
using Mango.Nop.Core.Entities;
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 MeasuringItemPalletBaseDbTable<TEntity>(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings) : MgDbTableBase<TEntity>(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings) where TEntity
    : MgEntityBase, IMeasuringItemPalletBase
{
    protected override void OnUpdate(TEntity entity)
    {
        BeforeInsertOrUpdate(entity);
        base.OnUpdate(entity);
    }

    protected override void OnInsert(TEntity entity)
    {
        BeforeInsertOrUpdate(entity);
        base.OnInsert(entity);
    }

    protected virtual void BeforeInsertOrUpdate(TEntity measuringItemPalletBase)
    {
        measuringItemPalletBase.GrossWeight = double.Round(measuringItemPalletBase.GrossWeight, 1);
        measuringItemPalletBase.TareWeight = double.Round(measuringItemPalletBase.TareWeight, 1);
        measuringItemPalletBase.PalletWeight = double.Round(measuringItemPalletBase.PalletWeight, 0);

        if (measuringItemPalletBase.IsValidSafeMeasuringValues()) return;

        throw new Exception($"MeasuringItemPalletBaseDbTable->BeforeInsertOrUpdate(); Invalid measuring value(s); {measuringItemPalletBase}");
    }
}