using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Events;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.UserCQ.EventHandlers;

public class UpdateUserEventHandler : INotificationHandler<UpdateUserEvent>
{
    private readonly ILogger<UpdateUserEventHandler> _logger;
    private readonly ITokenNotificationService _tokenNotificationService;

    public UpdateUserEventHandler(
        ILogger<UpdateUserEventHandler> logger,
        ITokenNotificationService tokenNotificationService)
    {
        _logger = logger;
        _tokenNotificationService = tokenNotificationService;
    }

    public async Task Handle(UpdateUserEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Domain Event: {DomainEvent} for User {UserId}", 
            notification.GetType().Name, 
            notification.Item.Id);

        // Notify connected clients that user profile has changed and token should be refreshed
        await _tokenNotificationService.NotifyForceRefreshAsync(notification.Item.Id);
    }
}
