using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace HRD.WebApi.Helpers
{
    public static class ExceptionExtension
    {
        public static void AddCustomExceptionHandling(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                    context.Response.ContentType = "application/json";
                    var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                    if (errorFeature != null)
                    {
                        HttpErrorDetails customError = new HttpErrorDetails
                        {
                            URI = context.Request.Path.ToUriComponent(),
                            Status = context.Response.StatusCode,
                            Detail = errorFeature.Error.Message
                        };

                        var loggerFactory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
                        ILogger logger = loggerFactory.CreateLogger("ExceptionExtension");
                        logger.LogError(errorFeature.Error, "An error occurred while processing the request. URI: {RequestUri}", customError.URI);
                        
                        await context.Response.WriteAsync(JsonConvert.Serialize(customError)).ConfigureAwait(false);
                    }
                });
            });
        }
    }
}