using System.Text.Json; using System.Text.Json.Serialization; namespace MeterVault.Infrastructure.Ingestion; /// /// The parsed JSON for a Home Assistant /// connection (SDD §6.2). The long-lived token is stored by reference only: /// names an environment variable resolved at runtime — never the token itself (SDD §6.4). /// public sealed record HaEndpointConfig { private static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; /// Base URL of the Home Assistant instance, e.g. http://homeassistant.local:8123. public string? BaseUrl { get; init; } /// Name of the environment variable holding the long-lived access token. public string? TokenEnv { get; init; } public static HaEndpointConfig Parse(string? json) { if (string.IsNullOrWhiteSpace(json)) { return new HaEndpointConfig(); } try { return JsonSerializer.Deserialize(json, Options) ?? new HaEndpointConfig(); } catch (JsonException) { return new HaEndpointConfig(); } } public string ToJson() => JsonSerializer.Serialize(this, Options); /// Resolves the token from the referenced environment variable (null if unset). public string? ResolveToken() => string.IsNullOrWhiteSpace(TokenEnv) ? null : Environment.GetEnvironmentVariable(TokenEnv); }