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

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

    public async Task Handle(TaskUpdatedEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Handling TaskUpdatedEvent for task {TaskId}", notification.TaskId);

        var taskData = new
        {
            Id = notification.TaskId.Value,
            ProjectId = notification.ProjectId.Value,
            StoryId = notification.StoryId.Value,
            Title = notification.TaskTitle,
            UpdatedAt = DateTime.UtcNow
        };

        await _notificationService.NotifyTaskUpdated(
            notification.TenantId.Value,
            notification.ProjectId.Value,
            notification.StoryId.Value,
            notification.TaskId.Value,
            taskData);

        _logger.LogInformation("SignalR notification sent for task {TaskId}", notification.TaskId);
    }
}
