using System.Text;
using System.Text.Json;

namespace StellaOps.Feedser.Models;

/// <summary>
/// Helper for tests/fixtures that need deterministic JSON snapshots.
/// </summary>
public static class SnapshotSerializer
{
    public static string ToSnapshot<T>(T value)
        => CanonicalJsonSerializer.SerializeIndented(value);

    public static void AppendSnapshot<T>(StringBuilder builder, T value)
    {
        ArgumentNullException.ThrowIfNull(builder);
        builder.AppendLine(ToSnapshot(value));
    }

    public static async Task WriteSnapshotAsync<T>(Stream destination, T value, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(destination);
        await using var writer = new StreamWriter(destination, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), leaveOpen: true);
        await writer.WriteAsync(ToSnapshot(value).AsMemory(), cancellationToken).ConfigureAwait(false);
        await writer.FlushAsync().ConfigureAwait(false);
    }
}
