using ValidationException = HiVakil.Common.Models.Exception.ValidationException;

namespace HiVakil.Repository.Behaviors;

public class ValidationBehavior <TRequest,TResponse> : IPipelineBehavior<TRequest,TResponse> where TRequest : notnull
{
    private readonly IEnumerable<IValidator<TRequest>> _validators;

    public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
    {
        _validators = validators;
    }
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        var context = new ValidationContext<TRequest>(request);
        List<ValidationError> errors = new List<ValidationError>();
        foreach (IValidator<TRequest> validator in _validators)
        {
            var result = await validator.ValidateAsync(context, cancellationToken);
            if (!result.IsValid)
                errors.AddRange(result.Errors.Select(v => new ValidationError(v.PropertyName, v.ErrorMessage)).Distinct());
        }

        if (errors.Any())
        {
            throw new ValidationException(errors);
        }


        var response = await next();
        return response;
    }
}