using Serilog.Core;
using Serilog.Events;

namespace IWS5.Importer.Worker.Extensions;

public class CorrelationIdEnricher : ILogEventEnricher
{
    private static AsyncLocal<string> _correlationId = new AsyncLocal<string>();

    public static void SetCorrelationId(string correlationId)
    {
        _correlationId.Value = correlationId;
    }

    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (logEvent.Exception != null)
        {
            logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("ExceptionType", logEvent.Exception.GetType().FullName));
            logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("ExceptionMessage", logEvent.Exception.Message));
            logEvent.AddOrUpdateProperty(propertyFactory.CreateProperty("ExceptionStackTrace", logEvent.Exception.StackTrace));
        }
        var correlationId = _correlationId.Value ?? Guid.NewGuid().ToString();
        logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("CorrelationId", correlationId));
    }
}

