using MediatR;
using Microsoft.Extensions.Logging;
using ColaFlow.Modules.ProjectManagement.Domain.Events;
using ColaFlow.Modules.ProjectManagement.Application.Services;

namespace ColaFlow.Modules.ProjectManagement.Application.EventHandlers;

/// <summary>
/// Handler for StoryUpdatedEvent - sends SignalR notification
/// </summary>
public class StoryUpdatedEventHandler : INotificationHandler<StoryUpdatedEvent>
{
    private readonly IProjectNotificationService _notificationService;
    private readonly ILogger<StoryUpdatedEventHandler> _logger;

    public StoryUpdatedEventHandler(
        IProjectNotificationService notificationService,
        ILogger<StoryUpdatedEventHandler> logger)
    {
        _notificationService = notificationService;
        _logger = logger;
    }

    public async Task Handle(StoryUpdatedEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Handling StoryUpdatedEvent for story {StoryId}", notification.StoryId);

        var storyData = new
        {
            Id = notification.StoryId.Value,
            ProjectId = notification.ProjectId.Value,
            EpicId = notification.EpicId.Value,
            Title = notification.StoryTitle,
            UpdatedAt = DateTime.UtcNow
        };

        await _notificationService.NotifyStoryUpdated(
            notification.TenantId.Value,
            notification.ProjectId.Value,
            notification.EpicId.Value,
            notification.StoryId.Value,
            storyData);

        _logger.LogInformation("SignalR notification sent for story {StoryId}", notification.StoryId);
    }
}
