using FluentValidation;
using PARR.API.Contracts.V1.Requests;
using PARR.DAL.Services.Interfaces;

namespace PARR.API.Validators
{
    public class SubprocessValidator : AbstractValidator<SubprocessRequest>
    {
        private readonly IProcessService processService;
        private bool? isValid = null;

        public SubprocessValidator(
            IProcessService processService
            )
        {
            this.processService = processService;

            RuleFor(t => t.Name).NotEmpty().NotNull();

            RuleFor(t => t.EsppId).NotEmpty().NotNull();

            RuleFor(t => t.ProcessId).NotEmpty().NotNull();

            RuleFor(t => t.ProcessId)
                .MustAsync(async (entity, value, c) => await IsProcessExist(entity))
                .WithMessage("Указан несуществующий Id процесса");
        }

        private async Task<bool> IsProcessExist(SubprocessRequest request)
        {
            //чтобы не делать 2 раза валидацию
            if (isValid.HasValue)
                return isValid.Value;

            isValid = await processService.GetAsync(request.ProcessId) != null;

            return isValid.Value;
        }
    }
}
