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

namespace ColaFlow.Modules.ProjectManagement.Application.EventHandlers;

/// <summary>
/// Handler for ProjectUpdatedEvent - sends SignalR notification
/// </summary>
public class ProjectUpdatedEventHandler : INotificationHandler<ProjectUpdatedEvent>
{
    private readonly IProjectNotificationService _notificationService;
    private readonly IProjectRepository _projectRepository;
    private readonly ILogger<ProjectUpdatedEventHandler> _logger;

    public ProjectUpdatedEventHandler(
        IProjectNotificationService notificationService,
        IProjectRepository projectRepository,
        ILogger<ProjectUpdatedEventHandler> logger)
    {
        _notificationService = notificationService;
        _projectRepository = projectRepository;
        _logger = logger;
    }

    public async Task Handle(ProjectUpdatedEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Handling ProjectUpdatedEvent for project {ProjectId}", notification.ProjectId);

        // Get full project to obtain TenantId
        var project = await _projectRepository.GetByIdAsync(notification.ProjectId, cancellationToken);
        if (project == null)
        {
            _logger.LogWarning("Project {ProjectId} not found for update notification", notification.ProjectId);
            return;
        }

        var projectData = new
        {
            Id = notification.ProjectId.Value,
            Name = notification.Name,
            Description = notification.Description,
            UpdatedAt = DateTime.UtcNow
        };

        await _notificationService.NotifyProjectUpdated(
            project.TenantId.Value,
            notification.ProjectId.Value,
            projectData);

        _logger.LogInformation("SignalR notification sent for updated project {ProjectId}", notification.ProjectId);
    }
}
