using EntityFrameworkCore.Triggered;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.Triggers
{

    // 统一处理  外部用户、中心调研(先添加 再发送邮件)、参与医生加入到项目  ----废弃
    public class AddlTrialUserTrigger : IBeforeSaveTrigger<TrialUser>

    {
        private readonly IRepository<Trial> _trialRepository;
        private readonly IRepository<User> _userRepository;

        public AddlTrialUserTrigger(IRepository<Trial> trialRepository, IRepository<User> userRepository)
        {
            _trialRepository = trialRepository;

            _userRepository = userRepository;

        }
        public async Task BeforeSave(ITriggerContext<TrialUser> context, CancellationToken cancellationToken)
        {
            var trialUser = context.Entity;

            if (context.ChangeType == ChangeType.Added)
            {
                //批量添加的时候，使用Find   不会多次查询，优先从跟踪的内存中查找
                var trialInfo = await _trialRepository.FindAsync(trialUser.TrialId);

                // 必须包在同一个事务，有的时候是数据库还没用户，不能直接查询数据库
                var user = await _userRepository.FindAsync(trialUser.UserId);

                if (trialInfo.TrialType == Domain.Share.TrialType.OfficialTrial || trialInfo.TrialType == Domain.Share.TrialType.Training)
                {

                    if (user.IsTestUser)
                    {
                        throw new BusinessValidationFailedException("正式类型 、培训类型的项目 不允许加入测试用户 ");

                    }
                }

                if (trialInfo.TrialType == TrialType.NoneOfficial)
                {

                    if (user.IsTestUser == false )
                    {
                        throw new BusinessValidationFailedException("测试项目  不允许加入正式用户 ");

                    }
                }
            }
        }
    }


}