using Core.Enumerations;
using ExtensionMethods;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Net;

namespace Core.Middlewares {

  /// <summary>
  /// https://jasonwatmore.com/post/2022/01/17/net-6-global-error-handler-tutorial-with-example
  /// </summary>
  public class ErrorHandlerMiddleware {
    private readonly ILogger<ErrorHandlerMiddleware> _logger;
    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(
      ILogger<ErrorHandlerMiddleware> 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());
      }
    }
  }
}
