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

namespace StellaOps.Scanner.WebService.Extensions;

/// <summary>
/// Scanner-specific configuration helpers.
/// </summary>
public static class ConfigurationExtensions
{
    public static IConfigurationBuilder AddScannerYaml(this IConfigurationBuilder builder, string path)
    {
        ArgumentNullException.ThrowIfNull(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 payload = JsonSerializer.Serialize(yamlObject);
        var stream = new MemoryStream(Encoding.UTF8.GetBytes(payload));
        return builder.AddJsonStream(stream);
    }
}
