using System.Text.Json;

namespace ZB.MOM.WW.ScadaBridge.DelmiaNotifier;

/// <summary>Reads and interprets the notifier's configuration and secret. Parse logic is string-based so it is unit-testable without touching disk.</summary>
internal static class ConfigLoader
{
    private const string ApiKeyEnvVar = "SCADABRIDGE_API_KEY";

    /// <summary>Deserialize the <c>appsettings.json</c> text via the source-gen context.</summary>
    /// <param name="jsonText">The raw JSON text of <c>appsettings.json</c>.</param>
    /// <returns>The deserialized <see cref="NotifierConfig"/>, or a default instance if deserialization yields <c>null</c>.</returns>
    public static NotifierConfig Load(string jsonText) =>
        JsonSerializer.Deserialize(jsonText, NotifierJsonContext.Default.NotifierConfig) ?? new NotifierConfig();

    /// <summary>Read and parse the <c>appsettings.json</c> sitting next to the executable.</summary>
    /// <returns>The deserialized <see cref="NotifierConfig"/>.</returns>
    public static NotifierConfig LoadFromDefaultFile()
    {
        var path = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
        return Load(File.ReadAllText(path));
    }

    /// <summary>Split a comma-separated base-URL list into trimmed, non-empty entries.</summary>
    /// <param name="baseUrls">The comma-separated base-URL list, or <c>null</c>/empty.</param>
    /// <returns>The trimmed, non-empty base URLs; an empty array if none.</returns>
    public static string[] SplitBaseUrls(string? baseUrls)
    {
        if (string.IsNullOrWhiteSpace(baseUrls))
        {
            return [];
        }

        return baseUrls.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
    }

    /// <summary>Resolve the API key from <c>SCADABRIDGE_API_KEY</c>; null/whitespace → null. Env accessor is injected for testability.</summary>
    /// <param name="envGet">Accessor used to read an environment variable by name.</param>
    /// <returns>The resolved API key, or <c>null</c> if unset/whitespace.</returns>
    public static string? ResolveApiKey(Func<string, string?> envGet)
    {
        var key = envGet(ApiKeyEnvVar);
        return string.IsNullOrWhiteSpace(key) ? null : key;
    }
}
