using IRaCIS.Core.Infrastructure.Extention;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;


namespace IRaCIS.Core.Application.Filter
{


    public class ModelActionFilter : ActionFilterAttribute, IActionFilter
    {
		public IStringLocalizer _localizer;
		public ModelActionFilter(IStringLocalizer localizer)
        {
			_localizer = localizer;
		}

		public override void OnActionExecuting(ActionExecutingContext context)
		{
            if (!context.ModelState.IsValid)
            {

                var validationErrors = context.ModelState
                                              .Keys
                                              .SelectMany(k => context.ModelState[k]!.Errors)
                                              .Select(e => e.ErrorMessage)
                                              .ToArray();
     
                //---提供给接口的参数无效。
                context.Result = new JsonResult(ResponseOutput.NotOk(_localizer["ModelAction_InvalidAPIParameter"] + JsonConvert.SerializeObject( validationErrors)));
            }
        }
    }

}
