using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text.Json.Nodes; namespace StellaOps.Notify.Models; /// /// Lightweight validation helpers shared across Notify model constructors. /// public static class NotifyValidation { public static string EnsureNotNullOrWhiteSpace(string value, string paramName) { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Value cannot be null or whitespace.", paramName); } return value.Trim(); } public static string? TrimToNull(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim(); public static ImmutableArray NormalizeStringSet(IEnumerable? values) => (values ?? Array.Empty()) .Where(static value => !string.IsNullOrWhiteSpace(value)) .Select(static value => value.Trim()) .Distinct(StringComparer.Ordinal) .OrderBy(static value => value, StringComparer.Ordinal) .ToImmutableArray(); public static ImmutableDictionary NormalizeStringDictionary(IEnumerable>? pairs) { if (pairs is null) { return ImmutableDictionary.Empty; } var builder = ImmutableSortedDictionary.CreateBuilder(StringComparer.Ordinal); foreach (var (key, value) in pairs) { if (string.IsNullOrWhiteSpace(key)) { continue; } var normalizedKey = key.Trim(); var normalizedValue = value?.Trim() ?? string.Empty; builder[normalizedKey] = normalizedValue; } return ImmutableDictionary.CreateRange(StringComparer.Ordinal, builder); } public static DateTimeOffset EnsureUtc(DateTimeOffset value) => value.ToUniversalTime(); public static DateTimeOffset? EnsureUtc(DateTimeOffset? value) => value?.ToUniversalTime(); public static JsonNode? NormalizeJsonNode(JsonNode? node) { if (node is null) { return null; } switch (node) { case JsonObject jsonObject: { var normalized = new JsonObject(); foreach (var property in jsonObject .Where(static pair => pair.Key is not null) .OrderBy(static pair => pair.Key, StringComparer.Ordinal)) { normalized[property.Key!] = NormalizeJsonNode(property.Value?.DeepClone()); } return normalized; } case JsonArray jsonArray: { var normalized = new JsonArray(); foreach (var element in jsonArray) { normalized.Add(NormalizeJsonNode(element?.DeepClone())); } return normalized; } default: return node.DeepClone(); } } }