using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly;
using Xunit;

namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests;

public sealed class ModbusTransportConfigRoundTripTests
{
    // Mirrors the AdminUI ModbusDriverForm serializer: camelCase + string enums.
    private static readonly JsonSerializerOptions _adminOpts = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        Converters = { new JsonStringEnumConverter() },
    };

    [Fact]
    public void Transport_serializes_as_a_string_not_a_number()
    {
        var opts = new ModbusDriverOptions { Host = "10.20.0.50", Port = 4001, Transport = ModbusTransportMode.RtuOverTcp };
        var json = JsonSerializer.Serialize(opts, _adminOpts);
        json.ShouldContain("\"transport\":\"RtuOverTcp\"");
        json.ShouldNotContain("\"transport\":1", Case.Sensitive);
    }

    [Fact]
    public void Factory_binds_RtuOverTcp_from_string_config()
    {
        const string json = """{ "host": "10.20.0.50", "port": 4001, "transport": "RtuOverTcp" }""";
        using var driver = ModbusDriverFactoryExtensions.CreateInstance("mb-rtu", json);
        var opts = (ModbusDriverOptions)typeof(ModbusDriver)
            .GetField("_options", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
            .GetValue(driver)!;
        opts.Transport.ShouldBe(ModbusTransportMode.RtuOverTcp);
    }

    [Fact]
    public void Factory_defaults_Transport_to_Tcp_when_omitted()
    {
        const string json = """{ "host": "10.0.0.10" }""";
        using var driver = ModbusDriverFactoryExtensions.CreateInstance("mb-tcp", json);
        var opts = (ModbusDriverOptions)typeof(ModbusDriver)
            .GetField("_options", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
            .GetValue(driver)!;
        opts.Transport.ShouldBe(ModbusTransportMode.Tcp);
    }
}
