using System.Text.Json;

namespace ZB.MOM.WW.ScadaBridge.CLI.Commands;

/// <summary>
/// Renders a page of audit-log events to a writer. The <c>audit query</c> command picks
/// a formatter from the <c>--format</c> option. The default JSONL formatter is defined
/// here; the human-readable table formatter is supplied by <see cref="TableAuditFormatter"/>.
/// </summary>
public interface IAuditFormatter
{
    /// <summary>Renders one page of events. Called once per fetched page.</summary>
    /// <param name="events">The audit events on this page.</param>
    /// <param name="output">Writer to render the formatted output to.</param>
    void WritePage(IReadOnlyList<JsonElement> events, TextWriter output);
}

/// <summary>
/// Default formatter: one JSON object per line (JSONL). Streamable — each page's events
/// are flushed as they arrive, so <c>--all</c> over many pages does not accumulate.
/// </summary>
public sealed class JsonLinesAuditFormatter : IAuditFormatter
{
    private static readonly JsonSerializerOptions Compact = new() { WriteIndented = false };

    /// <inheritdoc />
    public void WritePage(IReadOnlyList<JsonElement> events, TextWriter output)
    {
        foreach (var evt in events)
            output.WriteLine(JsonSerializer.Serialize(evt, Compact));
    }
}

/// <summary>
/// Resolves an <see cref="IAuditFormatter"/> for a given <c>--format</c> value:
/// <c>table</c> renders a column-aligned text table (<see cref="TableAuditFormatter"/>),
/// any other value (including <c>json</c>) renders JSONL.
/// </summary>
public static class AuditFormatterFactory
{
    /// <summary>
    /// Returns an <see cref="IAuditFormatter"/> for the given format name.
    /// </summary>
    /// <param name="format">Format name; <c>table</c> selects the table formatter, any other value selects JSONL.</param>
    /// <param name="notices">Writer for notice messages emitted during formatting.</param>
    /// <returns>The <see cref="IAuditFormatter"/> appropriate for the requested format.</returns>
    public static IAuditFormatter Create(string format, TextWriter notices)
    {
        if (string.Equals(format, "table", StringComparison.OrdinalIgnoreCase))
            return new TableAuditFormatter();

        return new JsonLinesAuditFormatter();
    }
}
