using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.KnowledgeBase;
using MediatR;
using Microsoft.Extensions.Logging;

namespace Hotline.Application.Handlers.FlowEngine;

public class WorkflowTerminalHandler : INotificationHandler<TerminalWorkflowNotify>
{
    private readonly IKnowledgeDomainService _knowledgeDomainService;
    private readonly ILogger<WorkflowTerminalHandler> _logger;

    public WorkflowTerminalHandler(
        IKnowledgeDomainService knowledgeDomainService,
        ILogger<WorkflowTerminalHandler> logger)
    {
        _knowledgeDomainService = knowledgeDomainService;
        _logger = logger;
    }

    /// <summary>Handles a notification</summary>
    /// <param name="notification">The notification</param>
    /// <param name="cancellationToken">Cancellation token</param>
    public async Task Handle(TerminalWorkflowNotify notification, CancellationToken cancellationToken)
    {
        try
        {
            var workflow = notification.Workflow;

            switch (workflow.ModuleCode)
            {
                case WorkflowModuleConsts.KnowledgeAdd://新增知识库
                case WorkflowModuleConsts.KnowledgeDelete://删除知识库
                    await _knowledgeDomainService.TerminateWorkKnowledge(workflow, cancellationToken);
                    break;
            }
        }
        catch (Exception e)
        {
            _logger.LogError($"{nameof(WorkflowTerminalHandler)}异常，{e}");
            throw;
        }
    }
}