using Serilog.Core;
using Serilog.Events;

namespace Predictalytics.Infrastructure.Logging;

/// <summary>
/// Custom Serilog sink that delegates log writes to a provided action.
/// The action is responsible for marshaling to the correct thread (e.g. UI thread).
/// </summary>
public class RichTextBoxSink : ILogEventSink
{
    private readonly Action<string, LogEventLevel> _writeAction;

    public RichTextBoxSink(Action<string, LogEventLevel> writeAction)
    {
        _writeAction = writeAction;
    }

    public void Emit(LogEvent logEvent)
    {
        var message = $"[{logEvent.Timestamp:HH:mm:ss}] [{logEvent.Level.ToString()[..3].ToUpper()}] {logEvent.RenderMessage()}";
        if (logEvent.Exception != null)
            message += $"\n  ⚠ {logEvent.Exception.Message}";

        _writeAction(message + "\n", logEvent.Level);
    }
}
