using System.Diagnostics;

namespace ColaFlow.API.Middleware;

/// <summary>
/// Middleware to log slow HTTP requests for performance monitoring
/// </summary>
public class PerformanceLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<PerformanceLoggingMiddleware> _logger;
    private readonly int _slowRequestThresholdMs;

    public PerformanceLoggingMiddleware(
        RequestDelegate next,
        ILogger<PerformanceLoggingMiddleware> logger,
        IConfiguration configuration)
    {
        _next = next;
        _logger = logger;
        _slowRequestThresholdMs = configuration.GetValue<int>("Performance:SlowRequestThresholdMs", 1000);
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var stopwatch = Stopwatch.StartNew();
        var requestPath = context.Request.Path;
        var requestMethod = context.Request.Method;

        try
        {
            await _next(context);
        }
        finally
        {
            stopwatch.Stop();
            var elapsedMs = stopwatch.ElapsedMilliseconds;

            // Log slow requests as warnings
            if (elapsedMs > _slowRequestThresholdMs)
            {
                _logger.LogWarning(
                    "Slow request detected: {Method} {Path} took {ElapsedMs}ms (Status: {StatusCode})",
                    requestMethod,
                    requestPath,
                    elapsedMs,
                    context.Response.StatusCode);
            }
            else if (elapsedMs > _slowRequestThresholdMs / 2)
            {
                // Log moderately slow requests as information
                _logger.LogInformation(
                    "Request took {ElapsedMs}ms: {Method} {Path} (Status: {StatusCode})",
                    elapsedMs,
                    requestMethod,
                    requestPath,
                    context.Response.StatusCode);
            }
        }
    }
}

/// <summary>
/// Extension method to register performance logging middleware
/// </summary>
public static class PerformanceLoggingMiddlewareExtensions
{
    public static IApplicationBuilder UsePerformanceLogging(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<PerformanceLoggingMiddleware>();
    }
}
