using System.Diagnostics;

namespace DocuMed.Api.WebFramework.MiddleWares;

public static class PerformanceMiddlewareExtensions
{
    public static IApplicationBuilder UsePerformanceMiddlewar(this IApplicationBuilder applicationBuilder)
    {
        return applicationBuilder.UseMiddleware<PerformanceMiddleware>();
    }
}

public class PerformanceMiddleware
{
    private readonly ILogger<ExceptionHandlerMiddleware> _logger;
    private readonly RequestDelegate _next;
    private readonly Stopwatch _timer;

    public PerformanceMiddleware(
        RequestDelegate next,
        ILogger<ExceptionHandlerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
        _timer = new Stopwatch();
    }

    public async System.Threading.Tasks.Task Invoke(HttpContext context)
    {
        _timer.Start();
        await _next(context);
        _timer.Stop();

        var elapsedMilliseconds = _timer.ElapsedMilliseconds;
        _logger.LogWarning($"REQUEST TIMER : {elapsedMilliseconds}");
    }
}