using FrameworkBLL.ActionProcessor.Handlers;
using GB5Shared.ActionProcessor;
using FrameworkSL.Hubs.EIPChat;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace FrameworkSL.Controllers.ActionProcessor;
///
/// ActionType = 5 — EIP Notification handler.
/// Delivers EIP conversation notifications to the active user session via
/// IHubContext<EIPChatHub>. The recipient group is appchat:user:{userId}:client:{clientId}.
///
public sealed class EipNotificationActionHandler : IActionHandler
{
public int ActionType => 5;
private readonly IHubContext _hub;
private readonly ILogger _logger;
public EipNotificationActionHandler(
IHubContext hub,
ILogger logger)
{
_hub = hub;
_logger = logger;
}
public async Task HandleAsync(ActionEventDto dto, CancellationToken ct = default)
{
if (dto is null)
return ActionResult.Permanent("ActionEventDto cannot be null");
// SendTo = RecipientId (UserId string); TenantId = ClientId
if (!int.TryParse(dto.SendTo, out var userId) || userId <= 0)
{
_logger.LogWarning(
"EipNotificationActionHandler: invalid RecipientId '{SendTo}' | ActionRunId={RunId}",
dto.SendTo, dto.ActionRunId);
return ActionResult.Permanent($"Invalid RecipientId: '{dto.SendTo}'");
}
string? message = null;
string? currentStep = null;
string? nextStep = null;
try
{
if (dto.Payload.ValueKind != JsonValueKind.Undefined)
{
message = dto.Payload.TryGetProperty("Message", out var m) ? m.GetString() : null;
currentStep = dto.Payload.TryGetProperty("CurrentStep", out var c) ? c.GetString() : null;
nextStep = dto.Payload.TryGetProperty("NextStep", out var n) ? n.GetString() : null;
}
}
catch (Exception ex)
{
_logger.LogWarning(ex, "EipNotificationActionHandler: payload parse warning | ActionRunId={RunId}", dto.ActionRunId);
}
var pushDto = new EIPChatMessageDTO
{
Message = message ?? string.Empty,
CurrentStepCode = currentStep,
NextStepCode = nextStep,
IsCompleted = false
};
var group = EIPChatHub.UserGroup(userId, dto.TenantId);
try
{
await _hub.Clients.Group(group)
.ReceiveBotMessage(pushDto)
.ConfigureAwait(false);
_logger.LogInformation(
"EipNotificationActionHandler: pushed to group {Group} | ActionRunId={RunId}",
group, dto.ActionRunId);
return ActionResult.Ok("delivered");
}
catch (Exception ex)
{
_logger.LogError(ex,
"EipNotificationActionHandler: SignalR push failed | Group={Group} ActionRunId={RunId}",
group, dto.ActionRunId);
return ActionResult.Transient(ex.Message);
}
}
}