using System;
using Microsoft.Extensions.Configuration;

namespace StellaOps.Configuration;

public static class StellaOpsOptionsBinder
{
    public static TOptions BindOptions<TOptions>(
        this IConfiguration configuration,
        string? section = null,
        Action<TOptions, IConfiguration>? postConfigure = null)
        where TOptions : class, new()
    {
        ArgumentNullException.ThrowIfNull(configuration);

        var options = new TOptions();
        var bindingSource = string.IsNullOrWhiteSpace(section)
            ? configuration
            : configuration.GetSection(section);

        bindingSource.Bind(options);
        postConfigure?.Invoke(options, configuration);

        return options;
    }
}
