namespace Mbproxy.Options;

/// <summary>
/// TCP keepalive and application-level connection-monitoring settings.
///
/// <para>The DL205/DL260 ECOM does not emit TCP keepalives, so an idle backend socket can be
/// silently dropped by a middlebox (switch, firewall, NAT) after 2-5 minutes. These knobs
/// (a) enable OS-level <c>SO_KEEPALIVE</c> on both backend and accepted upstream sockets and
/// (b) drive a periodic Modbus FC03 heartbeat on each idle backend socket so the path stays
/// warm and a dead ECOM is detected before a real client request hits it.</para>
/// </summary>
public sealed class KeepaliveOptions
{
    /// <summary>
    /// Master switch. When <c>false</c>, neither <c>SO_KEEPALIVE</c> nor the backend heartbeat
    /// is applied and the proxy behaves exactly as a pre-keepalive build. Default: <c>true</c>.
    /// </summary>
    public bool Enabled { get; init; } = true;

    /// <summary>
    /// <c>SO_KEEPALIVE</c> idle time in milliseconds — how long a socket may be idle before the
    /// OS sends its first keepalive probe. Applied to backend and accepted upstream sockets.
    /// Default: 30000 (30 s).
    /// </summary>
    public int TcpIdleTimeMs { get; init; } = 30000;

    /// <summary>
    /// <c>SO_KEEPALIVE</c> interval in milliseconds between keepalive probes once the idle time
    /// has elapsed. Default: 5000 (5 s).
    /// </summary>
    public int TcpProbeIntervalMs { get; init; } = 5000;

    /// <summary>
    /// <c>SO_KEEPALIVE</c> probe count — unanswered probes before the OS declares the socket
    /// dead. Default: 4.
    /// </summary>
    public int TcpProbeCount { get; init; } = 4;

    /// <summary>
    /// Backend application heartbeat: after this many milliseconds with no backend traffic, the
    /// multiplexer issues a synthetic FC03 qty=1 read to keep the socket warm and prove the ECOM
    /// is still answering Modbus. Must be greater than <see cref="ConnectionOptions.BackendRequestTimeoutMs"/>.
    /// Default: 30000 (30 s).
    /// </summary>
    public int BackendHeartbeatIdleMs { get; init; } = 30000;

    /// <summary>
    /// Modbus PDU address read by the backend heartbeat FC03 probe. Address 0 (V0) is valid on
    /// DL205/DL260 in factory absolute mode. Default: 0.
    /// </summary>
    public int BackendHeartbeatProbeAddress { get; init; } = 0;
}
