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

namespace Hotline.Application.OrderApp.Handlers.OrderScreenHandler;

public class OrderScreenStartWorkflowHandler : INotificationHandler<StartWorkflowNotify>
{
    private readonly IOrderScreenRepository _orderScreenRepository;

    public OrderScreenStartWorkflowHandler(
        IOrderScreenRepository orderScreenRepository
    )
    {
        _orderScreenRepository = orderScreenRepository;
    }

    /// <summary>Handles a notification</summary>
    /// <param name="notification">The notification</param>
    /// <param name="cancellationToken">Cancellation token</param>
    public async Task Handle(StartWorkflowNotify notification, CancellationToken cancellationToken)
    {
        if (notification.Workflow.ModuleCode == WorkflowModuleConsts.OrderScreen)
        {
            var workflow = notification.Workflow;
            var screen = await _orderScreenRepository.Queryable().Includes(x => x.Order)
                .Where(x => x.Id == workflow.ExternalId).FirstAsync(cancellationToken);
            if (screen != null)
            {
                screen.WorkflowId = workflow.Id;
                screen.Flowed(workflow.FlowedUserIds, workflow.FlowedOrgIds, workflow.HandlerUsers, workflow.HandlerOrgs);
                await _orderScreenRepository.UpdateAsync(screen, cancellationToken);
            }
        }
    }
}
