#if NET
using Microsoft.Extensions.Configuration;

namespace DigitalData.Core.Abstractions;

/// <summary>
/// Extension methods for the <see cref="IConfiguration"/> interface, providing 
/// additional functionality for retrieving configuration values with default behavior.
/// </summary>
public static class ConfigurationExtension
{
    /// <summary>
    /// Retrieves a configuration value for the specified key, or returns a default value 
    /// of type <typeparamref name="T"/> if the configuration is not found or the key is null.
    /// </summary>
    /// <typeparam name="T">The type of the object to retrieve from the configuration.</typeparam>
    /// <param name="configuration">The <see cref="IConfiguration"/> instance.</param>
    /// <param name="key">The optional key to look for in the configuration. If null, the method 
    /// retrieves the root configuration.</param>
    /// <returns>
    /// An instance of <typeparamref name="T"/> populated from the configuration values, or 
    /// a new instance of <typeparamref name="T"/> if no matching configuration is found.
    /// </returns>
    public static T GetOrDefault<T>(this IConfiguration configuration, string? key = null)
        where T : new()
        => (key is null
            ? configuration.Get<T>()
            : configuration.GetSection(key).Get<T>())
        ?? new T();
}
#endif