using Core.Enumerations;
using ExtensionMethods;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;
namespace Core.Middlewares {
  /// 
  /// https://jasonwatmore.com/post/2022/01/17/net-6-global-error-handler-tutorial-with-example
  /// 
  public class ErrorHandlerMiddleware {
    private readonly ILogger _logger;
    private readonly RequestDelegate _next;
    public ErrorHandlerMiddleware(
      ILogger logger,
      RequestDelegate next) {
      _logger = logger;
      _next = next;
    }
    public async Task Invoke(HttpContext context) {
      try {
        await _next(context);
      }
      catch (Exception ex) {
        _logger.LogError(ex, "Unhandled error");
        var response = context.Response;
        response.ContentType = "application/json";
        response.StatusCode = (int)HttpStatusCode.InternalServerError;
        await response.WriteAsync(new ProblemDetails {
          Title = Errors.Generic.Name,
          Detail = $"{Errors.Generic.Id}"
        }.ToJson());
      }
    }
  }
}