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

namespace Exam.Repository.Sqlsugar.Validators.Practices
{
    public class PracticeValidator : BaseValidator<ExamPractice>
    {
        private readonly IPracticeRepository _practiceRepository;

        public PracticeValidator(IPracticeRepository practiceRepository)
        {
            RuleSet(ValidatorTypeConstants.Create, () =>
            {
                BaseValidateRule();

                ValidateRuleWithAdd();
            });

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

                ValidateRuleWithModify();
            });
            this._practiceRepository = practiceRepository;
        }

        protected override void BaseValidateRule()
        {
            base.BaseValidateRule();
            RuleFor(m => m.Code).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamPractice.Code))));
        }

        protected override void ValidateRuleWithAdd()
        {
            base.ValidateRuleWithAdd();
            RuleFor(m => m.CreationTime).NotEmpty().WithMessage(x => string.Format(ExamErrorMessage.IsRequired, x.GetType().GetDescription(nameof(ExamPractice.CreationTime))));
            RuleFor(m => m.Code).Must(v => !_practiceRepository.Queryable().Any(x => x.Code == v)).WithMessage(x => string.Format(ExamErrorMessage.IsRepeat, x.GetType().GetDescription(nameof(ExamPractice.Code))));

        }

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

        }

    }
}
