using Mango.Nop.Core.Entities;
using Mango.Nop.Core.Repositories;
using Nop.Core.Caching;
using Nop.Core.Configuration;
using Nop.Core.Events;
using Nop.Data;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Entities;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Enums;
using Nop.Services.Logging;

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

public class AuctionDbTable : MgDbTableBase<Auction>
{
    public AuctionDbTable(IEventPublisher eventPublisher, INopDataProvider dataProvider, IShortTermCacheManager shortTermCacheManager, IStaticCacheManager staticCacheManager, AppSettings appSettings, ILogger logger)
        : base(eventPublisher, dataProvider, shortTermCacheManager, staticCacheManager, appSettings, logger)
    {
    }

    public IQueryable<Auction> GetAllAuctions()
    {
        return Table; //GetAllAsync(auctions => auctions.OrderByDescending(x => x.StartDateUtc), _ => default);
    }

    /// <summary>
    /// x.StartDateUtc <= utcNow && x.EndDateUtc >= utcNow
    /// </summary>
    /// <returns></returns>
    public IOrderedQueryable<Auction> GetAllCurrentAutoOpenAndClosedAuctions()
    {
        var utcNow = DateTime.UtcNow;

        return GetAllAuctions()
            .Where(x => x.AuctionType == AuctionType.AutomaticAll && x.StartDateUtc <= utcNow && x.StartDateUtc < x.EndDateUtc && (!x.Closed || (x.Closed && x.EndDateUtc >= utcNow)))
            .OrderByDescending(x => x.StartDateUtc);
    }
}