using Hotline.Caching.Interfaces;
using Hotline.Share.Dtos.FlowEngine;
using XF.Domain.Dependency;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.FlowEngine.WorkflowModules
{
    public class WfModuleDomainService : IWfModuleDomainService, IScopeDependency
    {
        private readonly IRepository<WorkflowModule> _repository;
        private readonly IWfModuleCacheManager _cacheManager;

        public WfModuleDomainService(
            IRepository<WorkflowModule> repository,
            IWfModuleCacheManager cacheManager)
        {
            _repository = repository;
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 将新增的工作流业务持久化
        /// </summary>
        /// <returns></returns>
        public async Task PersistenceModulesAsync(CancellationToken cancellationToken)
        {
            var exists = await _repository.Queryable().Select(d => d.Code).ToListAsync();
            var newModules = WorkflowModuleConsts.AllModules
                .Where(d => !exists.Contains(d.Code))
                .Select(d => new WorkflowModule(d.Code, d.Name, d.Remark))
                .ToList();
            await _repository.AddRangeAsync(newModules, cancellationToken);
        }

        /// <summary>
        /// 为工作流业务匹配或取消流程模板
        /// </summary>
        public async Task MatchDefinitionAsync(MatchDefinitionDto dto, CancellationToken cancellationToken)
        {
            var module = await _repository.GetAsync(d => d.Code == dto.Code, cancellationToken);
            if (module == null)
                throw UserFriendlyException.SameMessage("无效业务模块编码");
            module.DefinitionId = dto.DefinitionId;
            await _repository.UpdateAsync(module, cancellationToken);
            await _cacheManager.RemoveWorkflowModuleAsync(dto.Code, cancellationToken);
        }
    }
}
