namespace ZB.MOM.WW.OtOpcUa.Client.Shared.Helpers;

/// <summary>
///     Parses and normalizes failover URL sets for redundant OPC UA connections.
/// </summary>
public static class FailoverUrlParser
{
    /// <summary>
    ///     Parses a comma-separated failover URL string, prepending the primary URL.
    ///     Trims whitespace and deduplicates.
    /// </summary>
    /// <param name="primaryUrl">The primary endpoint URL.</param>
    /// <param name="failoverCsv">Optional comma-separated failover URLs.</param>
    /// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
    public static string[] Parse(string primaryUrl, string? failoverCsv)
    {
        if (string.IsNullOrWhiteSpace(failoverCsv))
            return [primaryUrl];

        var urls = new List<string> { primaryUrl };
        foreach (var url in failoverCsv.Split(',', StringSplitOptions.RemoveEmptyEntries))
        {
            var trimmed = url.Trim();
            if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
                urls.Add(trimmed);
        }

        return urls.ToArray();
    }

    /// <summary>
    ///     Builds a failover URL set from the primary URL and an optional array of failover URLs.
    /// </summary>
    /// <param name="primaryUrl">The primary endpoint URL.</param>
    /// <param name="failoverUrls">Optional failover URLs.</param>
    /// <returns>An array with the primary URL first, followed by unique failover URLs.</returns>
    public static string[] Parse(string primaryUrl, string[]? failoverUrls)
    {
        if (failoverUrls == null || failoverUrls.Length == 0)
            return [primaryUrl];

        var urls = new List<string> { primaryUrl };
        foreach (var url in failoverUrls)
        {
            var trimmed = url?.Trim();
            if (!string.IsNullOrEmpty(trimmed) && !urls.Contains(trimmed, StringComparer.OrdinalIgnoreCase))
                urls.Add(trimmed);
        }

        return urls.ToArray();
    }
}