namespace Kit.Helpers
{
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Routing;
    using System.Reflection;

    public static class MicrosoftAspNetCoreHttpHttpContextExtentions
    {
        public static bool NeedResponseJsonResult(this HttpContext context, Exception? ex = null)
        {
            var routeData = context.GetRouteData();
            var controllerName = routeData?.Values["controller"]?.ToString();
            var actionName = routeData?.Values["action"]?.ToString();

            MethodInfo? methodInfo = null;

            if (string.IsNullOrEmpty(controllerName) == false && string.IsNullOrEmpty(actionName) == false)
            {
                foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    Type? controllerType = assembly.GetTypes()?.FirstOrDefault(t => string.Equals(t.Name, $"{controllerName}Controller", StringComparison.OrdinalIgnoreCase));
                    if (controllerType != null)
                    {
                        methodInfo = controllerType.GetMethod(actionName);
                        break;
                    }
                }
            }

            if (methodInfo == null && ex?.TargetSite != null && ex.TargetSite is MethodInfo methodInfoEx)
            {
                methodInfo = methodInfoEx;
            }

            return methodInfo != null && methodInfo.ReturnType.Equals(typeof(JsonResult));
        }
    }
}