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

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.DeviceForms;

/// <summary>
///     Typed working model for a TwinCAT <c>Device</c>'s connection endpoint (the v3 endpoint→DeviceConfig
///     split). Authors the <b>PascalCase</b> <c>HostAddress</c> key (the AMS Net Id:port host string) that
///     <c>TwinCATDeviceOptions</c> binds — the exact casing the seed and runtime probe
///     (<c>PropertyNameCaseInsensitive</c>) expect. Preserves unrecognised keys across a load→save.
/// </summary>
public sealed class TwinCATDeviceModel
{
    /// <summary>AMS Net Id:port host string (e.g. <c>192.168.0.1.1.1:851</c>).</summary>
    public string HostAddress { get; set; } = "";

    private System.Text.Json.Nodes.JsonObject _bag = new();

    /// <summary>Loads a model from a DeviceConfig JSON string, defaulting absent keys and retaining
    /// every original key so fields this editor doesn't expose survive a load→save.</summary>
    /// <param name="json">The raw DeviceConfig JSON string, or null for a new/empty device.</param>
    /// <returns>The populated <see cref="TwinCATDeviceModel"/>.</returns>
    public static TwinCATDeviceModel FromJson(string? json)
    {
        var o = TagConfigJson.ParseOrNew(json);
        return new TwinCATDeviceModel
        {
            HostAddress = TagConfigJson.GetString(o, "HostAddress") ?? "",
            _bag = o,
        };
    }

    /// <summary>Serializes this model back to a DeviceConfig JSON string, writing the PascalCase endpoint
    /// key over the preserved key bag.</summary>
    /// <returns>The serialised DeviceConfig JSON string.</returns>
    public string ToJson()
    {
        TagConfigJson.Set(_bag, "HostAddress", HostAddress);
        return TagConfigJson.Serialize(_bag);
    }

    /// <summary>Validation hook; returns an error message or null when the model is valid.</summary>
    /// <returns>An error message describing the validation failure, or <c>null</c> when the model is valid.</returns>
    public string? Validate()
        => string.IsNullOrWhiteSpace(HostAddress) ? "Host address is required." : null;
}
