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

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

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

    public IQueryable<PreOrder> GetAll(bool loadRelations)
    {
        return loadRelations
            ? GetAll()
                .LoadWith(p => p.PreOrderItems)
            : GetAll();
    }

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

    public IQueryable<PreOrder> GetAllByCustomerIdAsync(int customerId, bool loadRelations)
        => GetAll(loadRelations).Where(p => p.CustomerId == customerId);

    public IQueryable<PreOrder> GetAllPendingAsync(bool loadRelations)
    {
        var pendingStatuses = new[] { PreOrderStatus.Pending, PreOrderStatus.PartiallyFulfilled };
        return GetAll(loadRelations).Where(p => pendingStatuses.Contains(p.Status));
    }
}
