using System.Runtime.InteropServices;

namespace NATS.Server.Configuration;

/// <summary>
/// Registers POSIX signal handlers for config reload.
/// Go reference: server/signal_unix.go, server/opts.go reload logic.
/// On SIGHUP, triggers config reload via ConfigReloader.
/// </summary>
public static class SignalHandler
{
    private static PosixSignalRegistration? _registration;

    /// <summary>
    /// Registers a SIGHUP handler that will call the provided reload callback.
    /// Go reference: server/signal_unix.go — handleSignals goroutine.
    /// </summary>
    /// <param name="onReload">Callback invoked when SIGHUP is received.</param>
    public static void Register(Action onReload)
    {
        ArgumentNullException.ThrowIfNull(onReload);
        _registration = PosixSignalRegistration.Create(PosixSignal.SIGHUP, _ =>
        {
            onReload();
        });
    }

    /// <summary>
    /// Unregisters the SIGHUP handler.
    /// </summary>
    public static void Unregister()
    {
        _registration?.Dispose();
        _registration = null;
    }

    /// <summary>
    /// Whether a SIGHUP handler is currently registered.
    /// </summary>
    public static bool IsRegistered => _registration is not null;
}
