using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Nop.Core.Domain.Orders;
using Nop.Services.Orders;
using Nop.Services.Common;
using System.Threading.Tasks;
using Nop.Core;
using Nop.Plugin.Misc.FruitBankPlugin.Services;

namespace Nop.Plugin.Misc.FruitBankPlugin.Filters
{
    public class PendingMeasurementCheckoutFilter : IAsyncActionFilter
    {
        private readonly IWorkContext _workContext;
        private readonly IOrderService _orderService;
        private readonly IOrderMeasurementService _orderMeasurementService;

        public PendingMeasurementCheckoutFilter(
            IWorkContext workContext,
            IOrderService orderService,
            IOrderMeasurementService orderMeasurementService)
        {
            _workContext = workContext;
            _orderService = orderService;
            _orderMeasurementService = orderMeasurementService;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // csak a ConfirmOrder action-nál kell ellenőrizni
            var actionName = context.ActionDescriptor.RouteValues["action"];
            var controllerName = context.ActionDescriptor.RouteValues["controller"];

            if (controllerName == "Checkout" && actionName == "ConfirmOrder")
            {
                // lekérjük a user aktuális kosarát
                var customer = await _workContext.GetCurrentCustomerAsync();
                var order = await _orderService.GetOrderByIdAsync((int)context.ActionArguments["orderId"]); // ha van orderId param

                if (order != null && await _orderMeasurementService.IsPendingMeasurementAsync(order))
                {
                    order.OrderStatus = OrderStatus.Processing;
                    order.PaymentStatus = Core.Domain.Payments.PaymentStatus.Pending;
                    context.Result = new RedirectToRouteResult(new
                    {
                        controller = "Checkout",
                        action = "PendingMeasurementWarning"
                    });
                    return; // itt kilépünk, a fizetés nem engedélyezett
                }
            }

            await next(); // mehet a többi pipeline
        }
    }
}

