using Cortex.Mediator.Commands;
using CortexMediatorDemo.API.CQRS.Commands;
using CortexMediatorDemo.API.Services;

namespace CortexMediatorDemo.API.CQRS.PipelineBehaviors;

/// <summary>
/// Represents a pipeline behavior for handling notifications within the command execution pipeline.
/// This behavior is primarily used to send notifications upon successful command execution
/// or handling exceptions during command processing.
/// </summary>
/// <typeparam name="TCommand">The type of the command being handled. Must implement <see cref="ICommand"/>.</typeparam>
public class NotificationPipelineBehavior<TCommand>(INotificationService notificationService)
    : ICommandPipelineBehavior<TCommand>
    where TCommand : ICommand
{
    private readonly INotificationService _notificationService = notificationService ?? throw new ArgumentNullException(nameof(notificationService));

    public async Task Handle(TCommand command, CommandHandlerDelegate next, CancellationToken cancellationToken)
    {
        try
        {
            await next();
            
            // Only notify on specific commands if needed
            if (command is BookPurchaseCommand bookCommand)
            {
                await _notificationService.SendNotification(
                    $"New book '{bookCommand.NewBook.Title}' has been added to the system");
            }
        }
        catch (Exception ex)
        {
            await _notificationService.SendNotification(
                $"Error occurred: {ex.Message}", isError: true);
            throw;
        }
    }
}
