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

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

        try
        {
            // Create notification DTO
            var notificationDto = new PendingChangeExpiredNotification
            {
                NotificationType = "PendingChangeExpired",
                PendingChangeId = notification.PendingChangeId,
                ToolName = notification.ToolName,
                TenantId = notification.TenantId,
                ExpiredAt = DateTime.UtcNow,
                Timestamp = DateTime.UtcNow
            };

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

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