using Hotline.FlowEngine.Notifications;
using Hotline.FlowEngine.WorkflowModules;
using Hotline.Orders;
using MapsterMapper;
using MediatR;

namespace Hotline.Application.Handlers.FlowEngine;

public class CancelHandler : INotificationHandler<CancelWorkflowNotify>
{
    private readonly IOrderDomainService _orderDomainService;
    private readonly IOrderRepository _orderRepository;
    private readonly IMapper _mapper;

    public CancelHandler(
        IOrderDomainService orderDomainService,
        IOrderRepository orderRepository,
        IMapper mapper)
    {
        _orderDomainService = orderDomainService;
        _orderRepository = orderRepository;
        _mapper = mapper;
    }

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

        switch (workflow.ModuleCode)
        {
            case WorkflowModuleConsts.OrderHandle:
            case WorkflowModuleConsts.OrderHandleSnapshot:
                var order = await _orderDomainService.GetOrderAsync(workflow.ExternalId, cancellationToken: cancellationToken);
                order.CheckIfFiled();
                order.Cancel();
                order.UpdateHandlingStatus(workflow.IsInCountersign);
				_mapper.Map(workflow, order);
                await _orderRepository.UpdateAsync(order, cancellationToken);
                break;
        }
    }
}