using EasyCaching.Core;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore;
using MediatR;

namespace IRaCIS.Core.Application.MediatR.Handlers
{

    public class TrialStateCacheRequest : IRequest<bool>
    {

    }
    public class TrialStateCacheHandler : IRequestHandler<TrialStateCacheRequest, bool>
    {     
        private readonly IRepository<Trial> _trialRepository;

        private readonly IEasyCachingProvider _provider;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        public TrialStateCacheHandler(IRepository<Trial> trialRepository, IEasyCachingProvider provider)
        {
            _trialRepository = trialRepository;

            _provider = provider;

        }

      
        public async Task<bool> Handle(TrialStateCacheRequest request, CancellationToken cancellationToken)
        {
            //项目启动，将项目状态缓存，因为hangfire 加入后台任务，还是向队列添加任务，执行都有延迟，效果不好
            var list = await _trialRepository.Select(t => new { TrialId = t.Id, TrialStatusStr = t.TrialStatusStr }).ToListAsync();

            // 每天都会有任务刷新状态，项目编辑 添加时 都会处理到缓存中
            list.ForEach(t => _provider.Set(t.TrialId.ToString(), t.TrialStatusStr, TimeSpan.FromDays(7)));


            return true;
        }
    }


}
