using System.Collections.Immutable;

namespace StellaOps.Excititor.Connectors.Abstractions;

/// <summary>
/// Builds deterministic metadata dictionaries for raw documents and logging scopes.
/// </summary>
public sealed class VexConnectorMetadataBuilder
{
    private readonly SortedDictionary<string, string> _values = new(StringComparer.Ordinal);

    public VexConnectorMetadataBuilder Add(string key, string? value)
    {
        if (!string.IsNullOrWhiteSpace(key) && !string.IsNullOrWhiteSpace(value))
        {
            _values[key] = value!;
        }

        return this;
    }

    public VexConnectorMetadataBuilder Add(string key, DateTimeOffset value)
        => Add(key, value.ToUniversalTime().ToString("O"));

    public VexConnectorMetadataBuilder AddRange(IEnumerable<KeyValuePair<string, string?>> items)
    {
        foreach (var item in items)
        {
            Add(item.Key, item.Value);
        }

        return this;
    }

    public ImmutableDictionary<string, string> Build()
        => _values.ToImmutableDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal);
}
