using MediatR;
using Microsoft.Extensions.Logging;

namespace Managing.Application.Shared.Behaviours
{
    public class UnhandledExceptionBehaviour<TRequest, TResponse> : IUnhandledExceptionBehaviour<TRequest, TResponse>
    {
        private readonly ILogger<TRequest> logger;

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

        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            try
            {
                return await next();
            }
            catch (Exception ex)
            {
                var requestName = typeof(TRequest).Name;

                // Log to standard logger with request details
                // This will be picked up by the global middleware for Sentry
                logger.LogError(ex, "Unhandled Exception for Request {RequestName} {@Request}", requestName, request);

                // Add MediatR context to the exception for better tracing
                ex.Data["RequestType"] = requestName;
                ex.Data["RequestHandler"] = typeof(TRequest).FullName;
                
                // Rethrow to allow global error handling middleware to handle the response
                throw;
            }
        }
    }
}
