using Diligent.WebAPI.Host.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;

namespace Diligent.WebAPI.Host.Middlewares
{
    public class ModelValidationMiddleware : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context) { }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var validationItems = context.ModelState
                    .Where(x => x.Value != null && x.Value.Errors.Count > 0)
                    .Select(x => new { Key = x.Key, Value = x.Value?.Errors.Select(e => e.ErrorMessage).First() })
                    .ToList();

                string msg = "";

                validationItems.ForEach(n => msg += n.Value + ". ");

                var response = new ErrorDetails
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Message = msg
                };
                context.Result = new BadRequestObjectResult(response);
            }
        }
    }
}
