using System.Text.Json;
namespace AttendanceHub.Sync.Configuration;
/// Heartbeat activation settings (from the config "heartbeat" section).
public sealed record HeartbeatConfig(bool Enabled, int IntervalSeconds)
{
/// Default cadence. Laravel's Device::isOnline() needs a gap under 120s, so 60s
/// leaves a full missed beat of headroom before a healthy device would be judged offline.
public const int DefaultIntervalSeconds = 60;
/// Laravel's own online threshold (Device::isOnline: last_seen_at within 120s).
/// An interval at or above this can never look online, which is why the validator rejects it.
public const int LaravelOnlineThresholdSeconds = 120;
///
/// Parse the "heartbeat" config section. A missing section means "not configured", which is
/// reported as disabled: the host must never invent reporting that was not asked for.
/// A malformed section is also disabled — the startup validator is what refuses a bad file,
/// so this path only has to avoid crashing.
///
public static HeartbeatConfig ParseFromFile(string configPath)
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(configPath));
if (!doc.RootElement.TryGetProperty("heartbeat", out var hb)
|| hb.ValueKind != JsonValueKind.Object)
return new HeartbeatConfig(false, DefaultIntervalSeconds);
var enabled = hb.TryGetProperty("enabled", out var en)
&& en.ValueKind == JsonValueKind.True;
var interval = hb.TryGetProperty("intervalSeconds", out var iv)
&& iv.ValueKind == JsonValueKind.Number
&& iv.TryGetInt32(out var parsed)
&& parsed > 0
? parsed
: DefaultIntervalSeconds;
return new HeartbeatConfig(enabled, interval);
}
catch (Exception)
{
return new HeartbeatConfig(false, DefaultIntervalSeconds);
}
}
}