using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Text.Json;

namespace Atomx.Admin.Middlewares
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;
        private readonly IWebHostEnvironment _environment;

        public ExceptionHandlingMiddleware(
            RequestDelegate next,
            ILogger<ExceptionHandlingMiddleware> logger,
            IWebHostEnvironment environment)
        {
            _next = next;
            _logger = logger;
            _environment = environment;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            _logger.LogError(exception, "未处理的异常: {Message}", exception.Message);

            var response = context.Response;
            response.ContentType = "application/json";

            var problemDetails = new ProblemDetails
            {
                Title = "发生错误",
                Status = (int)HttpStatusCode.InternalServerError,
                Instance = context.Request.Path
            };

            // 根据异常类型设置状态码
            switch (exception)
            {
                case UnauthorizedAccessException:
                    problemDetails.Status = (int)HttpStatusCode.Unauthorized;
                    problemDetails.Title = "未授权访问";
                    break;
                case KeyNotFoundException:
                    problemDetails.Status = (int)HttpStatusCode.NotFound;
                    problemDetails.Title = "资源未找到";
                    break;
                case ArgumentException:
                case InvalidOperationException:
                    problemDetails.Status = (int)HttpStatusCode.BadRequest;
                    problemDetails.Title = "无效请求";
                    break;
            }

            // 开发环境包含详细错误信息
            if (_environment.IsDevelopment())
            {
                problemDetails.Extensions.Add("exception", exception.Message);
                problemDetails.Extensions.Add("stackTrace", exception.StackTrace);
                problemDetails.Extensions.Add("innerException", exception.InnerException?.Message);
            }
            else
            {
                problemDetails.Detail = "处理您的请求时发生错误。请稍后重试。";
            }

            response.StatusCode = problemDetails.Status.Value;
            await response.WriteAsync(JsonSerializer.Serialize(problemDetails));
        }
    }
}
