using FluentValidation;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace AipGateway.API.Application.Pipeline.Middlewares.Behaviours 
{
    public class ValidationBehaviour
    {
        private readonly ILogger<ValidationBehaviour> _log;
        private readonly IEnumerable<IValidator<HttpRequest>> _validators;
        private readonly RequestDelegate _next;

        public ValidationBehaviour(ILogger<ValidationBehaviour> logger, IEnumerable<IValidator<HttpRequest>> validators, RequestDelegate next)
        {
            _log = logger;
            _validators = validators;
            _next = next;
            _log.LogError("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo: ValidationBehaviour");
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                //_log.LogError("ValidationBehaviour Invoke Before:");
                if (_validators.Any())
                {
                    var validationContext = new ValidationContext<HttpRequest>(context.Request);

                    var validationResults = await Task.WhenAll(
                        _validators.Select(v =>
                            v.ValidateAsync(validationContext)));

                    var validationFailures = validationResults
                        .Where(r => r.Errors.Any())
                        .SelectMany(r => r.Errors)
                        .ToList();

                    if (validationFailures.Any())
                        throw new ValidationException(validationFailures);
                }
                await _next.Invoke(context);
                //_log.LogError("ValidationBehaviour Invoke  After:");
                _log.LogError("ValidationBehaviour.........................................................................");
            }
            catch (Exception)
            {

                throw;
            }
        }
    }

}
