using ColaFlow.Modules.Mcp.Application.DTOs.Notifications;
using ColaFlow.Modules.Mcp.Application.Services;
using ColaFlow.Modules.Mcp.Domain.Events;
using MediatR;
using Microsoft.Extensions.Logging;

namespace ColaFlow.Modules.Mcp.Application.EventHandlers;

/// <summary>
/// Event handler that sends SignalR notifications when a PendingChange is applied
/// </summary>
public class PendingChangeAppliedNotificationHandler(
    IMcpNotificationService notificationService,
    ILogger<PendingChangeAppliedNotificationHandler> logger)
    : INotificationHandler<PendingChangeAppliedEvent>
{
    private readonly IMcpNotificationService _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
    private readonly ILogger<PendingChangeAppliedNotificationHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger));

    public async Task Handle(PendingChangeAppliedEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Handling PendingChangeAppliedEvent for notification - PendingChangeId={PendingChangeId}, Result={Result}",
            notification.PendingChangeId, notification.Result);

        try
        {
            // Create notification DTO
            var notificationDto = new PendingChangeAppliedNotification
            {
                NotificationType = "PendingChangeApplied",
                PendingChangeId = notification.PendingChangeId,
                ToolName = notification.ToolName,
                Result = notification.Result,
                AppliedAt = DateTime.UtcNow,
                TenantId = notification.TenantId,
                Timestamp = DateTime.UtcNow
            };

            // Send notification via SignalR
            await _notificationService.NotifyPendingChangeAppliedAsync(notificationDto, cancellationToken);

            _logger.LogInformation(
                "PendingChangeApplied notification sent successfully - PendingChangeId={PendingChangeId}",
                notification.PendingChangeId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "Failed to send PendingChangeApplied notification - PendingChangeId={PendingChangeId}",
                notification.PendingChangeId);
            // Don't rethrow - notification failure shouldn't break the main flow
        }
    }
}
