using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace DigitalData.Core.Exceptions.Middleware;

public static class DependencyInjection
{
    public static IServiceCollection ConfigureGlobalExceptionHandler(this IServiceCollection services, Action<GlobalExceptionHandlerOptions>? options = null, bool addDefaultHandlers = true)
    {
        options ??= opt => { };

        if (addDefaultHandlers)
        {
            options += opt => opt.Add(HttpExceptionHandler.Default, setAsDefault: true);
            options += opt => opt.Add(HttpExceptionHandler.DefaultBadRequest);
            options += opt => opt.Add(HttpExceptionHandler.DefaultNotFound);
        }
        return services.Configure(options);
    }

    public static IApplicationBuilder UseGlobalExceptionHandler(this IApplicationBuilder app)
    {
        app.UseMiddleware<GlobalExceptionHandlerMiddleware>();
        return app;
    }
}