using Exam.Infrastructure.Extensions;
using Exam.Infrastructure.Validation.Validation;
using FluentValidation;
using Hotline.Exams.Trains;
using Hotline.Exams.Validate;
using Hotline.Repository.SqlSugar.Exam.Interfaces.Trains;
using Hotline.Repository.SqlSugar.Exam.Validate;

namespace Exam.Repository.Sqlsugar.Validators.Trains
{
    public class TrainPlanValidator:BaseValidator<ExamTrainPlan>
    {
        private readonly ITrainPlanRepository _trainPlanRepository;

        public TrainPlanValidator(ITrainPlanRepository trainPlanRepository)
        {
            RuleSet(ValidatorTypeConstants.Create, () =>
            {
                BaseValidateRule();

                ValidateRuleWithAdd();
            });

            RuleSet(ValidatorTypeConstants.Modify, () =>
            {
                BaseValidateRule();

                ValidateRuleWithModify();
            });
            this._trainPlanRepository = trainPlanRepository;
        }

        protected override void BaseValidateRule()
        {
            base.BaseValidateRule();
        }

        protected override void ValidateRuleWithAdd()
        {
            base.ValidateRuleWithAdd();
            RuleFor(m => m.CreationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamTrainPlan.CreationTime))));
            RuleFor(m => m.Name).Must((t, v) => !_trainPlanRepository.Queryable().Any(x => x.Name == v && x.Id != t.Id)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamTrainPlan.Name))));

            RuleFor(m=>m.Code).Must(v =>!_trainPlanRepository.Queryable().Any(x=>x.Code == v)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamTrainPlan.Code))));
        }

        protected override void ValidateRuleWithModify()
        {
            base.ValidateRuleWithModify();
            RuleFor(m => m.LastModificationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamTrainPlan.LastModificationTime))));
            RuleFor(m => m.Name).Must((t, v) => !_trainPlanRepository.Queryable().Any(x => x.Name == v && x.Id != t.Id)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamTrainPlan.Name))));

            RuleFor(m => m.Code).Must((t,v) => !_trainPlanRepository.Queryable().Any(x => x.Code == v && x.Id!=t.Id)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamTrainPlan.Code))));

        }

    }
}
