using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Memory;
namespace e_suite.Service.Performance.Extensions.Web;

public class PerformanceActionParamMaperFilter : ActionFilterAttribute
{
    private readonly IMemoryCache _memoryCache;

    public PerformanceActionParamMaperFilter(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var traceId = context.HttpContext.TraceIdentifier;
        var report = _memoryCache.Get<PerformanceCapture>(traceId);

        if (context.Filters.Any(f => f.GetType() == typeof(PerformanceMonitorFilterDisabler)))
        {
            var disabledRes = new Dictionary<string, object>
            {
                { "DisabledFilter", "ActionsParams are disabled for this Action" }
            };
            report!.ActionParameters = disabledRes;
        }
        else
        {
            report!.ActionParameters = context.ActionArguments!;
        }

        _memoryCache.Set(traceId, report);
        return base.OnActionExecutionAsync(context, next);
    }
}
