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

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

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

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

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

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