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(
    IProjectNotificationService notificationService,
    IProjectRepository projectRepository,
    ILogger<ProjectArchivedEventHandler> logger)
    : INotificationHandler<ProjectArchivedEvent>
{
    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);
    }
}
