using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace StellaOps.Feedser.WebService.Extensions;

public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddFeedserYaml(this IConfigurationBuilder builder, string path)
    {
        if (builder is null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
        {
            return builder;
        }

        var deserializer = new DeserializerBuilder()
            .WithNamingConvention(CamelCaseNamingConvention.Instance)
            .Build();

        using var reader = File.OpenText(path);
        var yamlObject = deserializer.Deserialize(reader);
        if (yamlObject is null)
        {
            return builder;
        }

        var json = JsonSerializer.Serialize(yamlObject);
        var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
        return builder.AddJsonStream(stream);
    }
}
