namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;

/// <summary>Extracts the driver-side <c>FullName</c> from a <c>Tag.TagConfig</c> JSON blob.
/// Mirrors <c>ScriptTagCatalog.ExtractFullNameFromTagConfig</c> (kept as a small local copy so
/// VirtualTag validation does not depend on the ScriptAnalysis catalog). Falls back to the raw
/// blob when it is not a JSON object with a string <c>FullName</c>.</summary>
internal static class TagConfigFullName
{
    /// <summary>Extract the FullName, or the raw blob when absent.</summary>
    /// <param name="tagConfig">The Tag.TagConfig JSON.</param>
    /// <returns>The FullName string, or the raw blob.</returns>
    public static string Extract(string? tagConfig)
    {
        if (string.IsNullOrWhiteSpace(tagConfig)) return tagConfig ?? string.Empty;
        try
        {
            using var doc = System.Text.Json.JsonDocument.Parse(tagConfig);
            if (doc.RootElement.ValueKind == System.Text.Json.JsonValueKind.Object
                && doc.RootElement.TryGetProperty("FullName", out var fullName)
                && fullName.ValueKind == System.Text.Json.JsonValueKind.String)
            {
                return fullName.GetString() ?? tagConfig;
            }
        }
        catch (System.Text.Json.JsonException) { /* fall through */ }
        return tagConfig;
    }
}
