using DocumentFormat.OpenXml.Office2010.Drawing;
using Mango.Nop.Services;
using Microsoft.AspNetCore.Http;
using Nop.Core.Domain.Catalog;
using Nop.Core.Events;
using Nop.Plugin.Misc.AuctionPlugin.Domains.DataLayer;
using Nop.Plugin.Misc.AuctionPlugin.Domains.Enums;
using Nop.Services.Logging;

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

public class AuctionEventConsumer(IHttpContextAccessor httpContextAccessor, ILogger logger, AuctionDbContext ctx) : MgEventConsumer(httpContextAccessor, logger)
{
    public override async Task HandleEventAsync(EntityUpdatedEvent<Product> eventMessage)
    {
        await Logger.InformationAsync($"AuctionEventConsumer.HandleEventAsync<Product>();");

        var productToAuctions = await ctx.ProductToAuctions.GetByProductId(eventMessage.Entity.Id).Where(x => x.AuctionStatus == AuctionStatus.None && x.OrderId == 0 && x.OrderItemId == 0).ToListAsync();

        foreach (var productToAuction in productToAuctions)
        {
            if (productToAuction.BidsCount > 0) //await ctx.HasBidByProductToAuctionIdAsync(productToAuction.Id))
            {
                await Logger.InformationAsync($"AuctionEventConsumer.HandleEventAsync<Product>(); HasAuctionBids->continue; productId: {eventMessage.Entity.Id}; productToAuctionId: {productToAuction.Id};");
                continue;
            }

            await ctx.ProductToAuctions.ResetAsync(productToAuction, eventMessage.Entity.Price);
        }

        await base.HandleEventAsync(eventMessage);
    }
}