using Serilog;
using Serilog.Debugging;
using Serilog.Events;

namespace Mbproxy.Diagnostics;

/// <summary>
/// Wires the local-syslog sink for <c>Error</c>+ events when mbproxy runs as a
/// systemd service on Linux — the cross-platform counterpart of
/// <see cref="EventLogBridge"/>.
///
/// <para>Events at <see cref="LogEventLevel.Error"/> and above are written to the
/// local syslog socket (<c>/dev/log</c>) under the application name
/// <see cref="AppName"/>, with Serilog levels mapped to syslog severities by the
/// sink. On a systemd host the local syslog socket is provided by
/// <c>systemd-journald</c>, so these events land in the journal at
/// <c>err</c>/<c>crit</c> priority — distinct from the process's stdout, which
/// journald captures at <c>info</c>.</para>
///
/// <para>If the local syslog socket is unavailable the bridge degrades silently
/// to the console (and rolling-file) sinks rather than failing logger
/// construction, mirroring <see cref="EventLogBridge"/>'s no-op-when-unavailable
/// contract.</para>
/// </summary>
internal static class SyslogBridge
{
    /// <summary>syslog application name — the <c>TAG</c> field of each entry.</summary>
    internal const string AppName = "mbproxy";

    /// <summary>
    /// Attaches the <c>Error</c>+ local-syslog sink to <paramref name="cfg"/> and
    /// returns it for fluent chaining. Never throws: a host where the syslog sink
    /// cannot be configured degrades to <paramref name="cfg"/> unchanged.
    /// </summary>
    public static LoggerConfiguration AttachTo(LoggerConfiguration cfg)
    {
        try
        {
            return cfg.WriteTo.LocalSyslog(
                appName: AppName,
                restrictedToMinimumLevel: LogEventLevel.Error);
        }
        catch (Exception ex)
        {
            // Degrade to console-only rather than crash logger construction.
            SelfLog.WriteLine("SyslogBridge: local syslog unavailable, console-only: {0}", ex);
            return cfg;
        }
    }
}
