using DotNetCore.CAP;
using Hotline.FlowEngine.Notifications;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Mq;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hotline.Orders;
using MapsterMapper;
using XF.Domain.Exceptions;

namespace Hotline.Application.Handlers.FlowEngine
{
    public class RedoHandler : INotificationHandler<RedoNotify>
    {
        private readonly IOrderDomainService _orderDomainService;
        private readonly IOrderRepository _orderRepository;
        private readonly ICapPublisher _capPublisher;
        private readonly IMapper _mapper;

        public RedoHandler(
            IOrderDomainService orderDomainService,
            IOrderRepository orderRepository,
            ICapPublisher capPublisher,
            IMapper mapper)
        {
            _orderDomainService = orderDomainService;
            _orderRepository = orderRepository;
            _capPublisher = capPublisher;
            _mapper = mapper;
        }

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

            var order = await _orderDomainService.GetOrderAsync(workflow.ExternalId, cancellationToken: cancellationToken);
            if (order is null)
                throw new UserFriendlyException("无效工单编号");

            order.Redo();
            await _orderRepository.UpdateAsync(order, cancellationToken);
        }
    }
}
