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

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

    public async Task Handle(ProjectArchivedEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Handling ProjectArchivedEvent 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 archive notification", notification.ProjectId);
            return;
        }

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

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