using Cortex.Mediator.Commands;
using Cortex.Mediator.Queries;
using Serilog;

namespace CortexMediatorDemo.API.CQRS.PipelineBehaviors;

/// <summary>
/// Represents a logging behavior for a command pipeline in the Cortex Mediator framework.
/// Logs the start, success, and failure of command execution.
/// </summary>
/// <typeparam name="TCommand">The type of the command being handled by the pipeline behavior.</typeparam>
public class LoggingPipelineBehavior<TCommand> : ICommandPipelineBehavior<TCommand> 
    where TCommand : ICommand
{
    public async Task Handle(TCommand command, CommandHandlerDelegate next, CancellationToken cancellationToken)
    {
        var commandName = typeof(TCommand).Name;
        try
        {
            Log.Information("##Starting execution of {CommandName}", commandName);
            
            await next();
            
            Log.Information("##Successfully completed {CommandName}", commandName);
        }
        catch (Exception ex)
        {
            Log.Error(ex, "##Error executing {CommandName}: {ErrorMessage}", commandName, ex.Message);
            throw;
        }
    }

}

public class LoggingPipelineBehavior<TQuery, TResult> : IQueryPipelineBehavior<TQuery, TResult> 
    where TQuery : IQuery<TResult>
{
    public async Task<TResult> Handle(TQuery query, QueryHandlerDelegate<TResult> next, CancellationToken cancellationToken)
    {
        var queryName = typeof(TQuery).Name;
        try
        {
            Log.Information("##Starting execution of {QueryName}", queryName);
            
            var result = await next();
            
            Log.Information("##Successfully completed {QueryName}", queryName);
            return result;
        }
        catch (Exception ex)
        {
            Log.Error(ex, "##Error executing {QueryName}: {ErrorMessage}", queryName, ex.Message);
            throw;
        }
    }

}

