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

/// <summary>
/// Client-side TagConfig validation dispatched by <c>DriverType</c> (parallel to
/// <see cref="TagConfigEditorMap"/>). Each entry parses the tag's config JSON into the driver's typed
/// model and runs its <c>Validate()</c>. Returns an error string to block the TagModal save, or null
/// when the config is valid — or when no typed validator is registered (unmapped drivers use the raw
/// textarea and are validated server-side at deploy).
/// </summary>
public static class TagConfigValidator
{
    private static readonly IReadOnlyDictionary<string, Func<string?, string?>> Validators =
        new Dictionary<string, Func<string?, string?>>(StringComparer.OrdinalIgnoreCase)
        {
            ["ModbusTcp"] = j => ModbusTagConfigModel.FromJson(j).Validate(),
            ["S7"]        = j => S7TagConfigModel.FromJson(j).Validate(),
            ["AbCip"]     = j => AbCipTagConfigModel.FromJson(j).Validate(),
            ["AbLegacy"]  = j => AbLegacyTagConfigModel.FromJson(j).Validate(),
            ["TwinCat"]   = j => TwinCATTagConfigModel.FromJson(j).Validate(),
            ["Focas"]     = j => FocasTagConfigModel.FromJson(j).Validate(),
        };

    /// <summary>
    /// Validates a tag's <paramref name="configJson"/> for the given <paramref name="driverType"/>.
    /// Returns an error string to block save, or null when valid / no typed validator is registered.
    /// </summary>
    public static string? Validate(string? driverType, string? configJson)
        => driverType is not null && Validators.TryGetValue(driverType, out var v) ? v(configJson) : null;
}
