using Microsoft.Extensions.Logging;
using OmsorgCore.Application.Abstractions;
using OmsorgCore.Engine.Events;

namespace OmsorgCore.Engine.Handlers;

public class UserInvitedHandler : IDomainEventHandler<UserInvitedEvent>
{
    private readonly IEmailSender _emailSender;
    private readonly IUserInviteEmailComposer _emailComposer;
    private readonly ILogger<UserInvitedHandler> _logger;

    public UserInvitedHandler(
        IEmailSender emailSender,
        IUserInviteEmailComposer emailComposer,
        ILogger<UserInvitedHandler> logger)
    {
        _emailSender = emailSender;
        _emailComposer = emailComposer;
        _logger = logger;
    }

    public async Task HandleAsync(UserInvitedEvent domainEvent, CancellationToken cancellationToken = default)
    {
        var message = _emailComposer.Compose(domainEvent.ToEmail, domainEvent.RawPin, domainEvent.ValidityDays);
        await _emailSender.SendAsync(message, cancellationToken);

        _logger.LogInformation("Engine: Account-Einladung an {Email} versendet ({OccurredAt}).",
            domainEvent.ToEmail, domainEvent.OccurredAt);
    }
}
