using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ZB.MOM.WW.MxGateway.Worker.Bootstrap;

public sealed class WorkerConsoleLogger : IWorkerLogger
{
    private readonly TextWriter _writer;

    /// <summary>Initializes a new worker console logger.</summary>
    /// <param name="writer">Text writer destination for log output.</param>
    public WorkerConsoleLogger(TextWriter writer)
    {
        _writer = writer ?? throw new ArgumentNullException(nameof(writer));
    }

    /// <inheritdoc />
    public void Information(string eventName, IReadOnlyDictionary<string, object?> fields)
    {
        Write("Information", eventName, fields);
    }

    /// <inheritdoc />
    public void Error(string eventName, IReadOnlyDictionary<string, object?> fields)
    {
        Write("Error", eventName, fields);
    }

    private void Write(
        string level,
        string eventName,
        IReadOnlyDictionary<string, object?> fields)
    {
        Dictionary<string, object?> redactedFields = WorkerLogRedactor.RedactFields(fields);
        string fieldText = string.Join(
            " ",
            redactedFields.Select(field => $"{field.Key}={FormatValue(field.Value)}"));

        _writer.WriteLine($"level={level} event={eventName} {fieldText}".TrimEnd());
    }

    private static string FormatValue(object? value)
    {
        return value?.ToString() ?? string.Empty;
    }
}
