using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Diagnostics;

namespace QYZH.InteractiveMagazine.Infrastructure.Middleware;

/// <summary>
/// 操作日志中间件
/// </summary>
public class OperationLogMiddleware : IMiddleware
{
    private readonly ILogger<OperationLogMiddleware> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger">日志记录器</param>
    public OperationLogMiddleware(ILogger<OperationLogMiddleware> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 执行中间件
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="next">下一个中间件委托</param>
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        var stopwatch = Stopwatch.StartNew();

        var requestMethod = context.Request.Method;
        var requestUrl = context.Request.Path.ToString();

        try
        {
            await next(context);
        }
        finally
        {
            stopwatch.Stop();
            var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;

            _logger.LogInformation(
                "请求完成 | {Method} {Url} | 状态码: {StatusCode} | 耗时: {ElapsedMilliseconds}ms",
                requestMethod,
                requestUrl,
                context.Response.StatusCode,
                elapsedMilliseconds
            );
        }
    }
}
