using Serilog.Core;
using Serilog.Events;

namespace Predictalytics.Hosting;

/// <summary>
/// Serilog sink that forwards Error and Fatal events to the Deployment Center error stream.
///
/// It is registered while the logger is being built, long before the settings are known —
/// <see cref="DcErrorReporter"/> is asked at emit time whether reporting is switched on, so
/// toggling the setting takes effect without rebuilding the logger.
/// </summary>
public sealed class DcErrorSink : ILogEventSink
{
    public void Emit(LogEvent logEvent)
    {
        if (logEvent.Level < LogEventLevel.Error) return;
        if (!DcErrorReporter.IsEnabled) return;

        var level = logEvent.Level == LogEventLevel.Fatal ? "fatal" : "error";

        if (logEvent.Exception is not null)
        {
            DcErrorReporter.Report(logEvent.Exception, level);
            return;
        }

        // No exception attached: the rendered message is all the identity this error has.
        var source = logEvent.Properties.TryGetValue("SourceContext", out var ctx)
            ? ctx.ToString().Trim('"')
            : "Predictalytics";

        DcErrorReporter.ReportMessage(
            exceptionType: source,
            message: logEvent.RenderMessage(),
            stackTrace: null,
            level: level);
    }
}
