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 rejected
/// </summary>
public class PendingChangeRejectedNotificationHandler(
    IMcpNotificationService notificationService,
    ILogger<PendingChangeRejectedNotificationHandler> logger)
    : INotificationHandler<PendingChangeRejectedEvent>
{
    private readonly IMcpNotificationService _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));
    private readonly ILogger<PendingChangeRejectedNotificationHandler> _logger = logger ?? throw new ArgumentNullException(nameof(logger));

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

        try
        {
            // Create notification DTO
            var notificationDto = new PendingChangeRejectedNotification
            {
                NotificationType = "PendingChangeRejected",
                PendingChangeId = notification.PendingChangeId,
                ToolName = notification.ToolName,
                Reason = notification.Reason,
                RejectedBy = notification.RejectedBy,
                TenantId = notification.TenantId,
                Timestamp = DateTime.UtcNow
            };

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

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