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 StoryCreatedEvent - sends SignalR notification
/// </summary>
public class StoryCreatedEventHandler : INotificationHandler<StoryCreatedEvent>
{
    private readonly IProjectNotificationService _notificationService;
    private readonly ILogger<StoryCreatedEventHandler> _logger;

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

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

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

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

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