using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.Common.Behaviours;

public class UnhandledExceptionBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : IRequest<TResponse>
{
    private readonly ILogger<TRequest> _logger;

    public UnhandledExceptionBehaviour(ILogger<TRequest> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next,
        CancellationToken cancellationToken)
    {
        try
        {
            return await next();
        }
        catch (Exception ex)
        {
            var requestName = typeof(TRequest).Name;
            var safeLog = request?.ToString() ?? "";
            if (safeLog.Length > 2000)
                safeLog = safeLog[..2000] + "... [TRUNCATED]";

            _logger.LogError(ex, "Request: Unhandled Exception for Request {Name} {Request}", requestName, safeLog);

            throw;
        }
    }
}
