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

    public IQueryable<PreOrderItem> GetAllByPreOrderIdAsync(int preorderId)
        => GetAll().Where(i => i.PreOrderId == preorderId);

    public IQueryable<PreOrderItem> GetAllByProductIdAsync(int productId)
        => GetAll().Where(i => i.ProductId == productId);

    /// <summary>
    /// All pending/partially-fulfilled items for a product, ordered by their parent preorder's
    /// CreatedOnUtc for first-come-first-served allocation.
    /// </summary>
    public IQueryable<PreOrderItem> GetPendingByProductIdOrderedAsync(int productId)
    {
        var pendingStatuses = new[] { PreOrderItemStatus.Pending, PreOrderItemStatus.PartiallyFulfilled };
        return GetAll()
            .Where(i => i.ProductId == productId && pendingStatuses.Contains(i.Status))
            .OrderBy(i => i.PreOrderId);
    }
}
