using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;

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

/// <summary>
///     CONV-4 (Modbus leg) — Modbus keys per-host resilience per SLAVE UNIT
///     (<c>host:port/unitN</c>). An authored raw tag carries its own <c>unitId</c> in its TagConfig so
///     multi-unit tags key their own breaker; <see cref="ModbusDriver.ResolveHost"/> resolves a RawPath
///     through the driver's authored RawPath → definition table. Under v3 the reference is always a
///     RawPath — an unauthored RawPath falls back to the driver-level host.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusUnitIdResolveHostTests
{
    private sealed class NoopTransport : IModbusTransport
    {
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
            => Task.FromResult(new byte[] { 0x03, 0x00 });
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    private static async Task<ModbusDriver> NewDriverAsync(params RawTagEntry[] rawTags)
    {
        var drv = new ModbusDriver(
            new ModbusDriverOptions
            {
                Host = "10.0.0.1", Port = 502, UnitId = 1, RawTags = rawTags,
                Probe = new ModbusProbeOptions { Enabled = false },
            },
            "modbus-1", _ => new NoopTransport());
        await drv.InitializeAsync("{}", CancellationToken.None);
        return drv;
    }

    /// <summary>The mapper reads an optional unitId into the definition.</summary>
    [Fact]
    public void FromTagConfig_reads_optional_unitId()
    {
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U7", out var def).ShouldBeTrue();
        def.Name.ShouldBe("cell/modbus/dev1/U7");
        def.UnitId.ShouldBe((byte)7);
    }

    /// <summary>An absent unitId leaves the definition on the driver-level default (null override).</summary>
    [Fact]
    public void FromTagConfig_absent_unitId_is_null()
    {
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}""";
        ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U0", out var def).ShouldBeTrue();
        def.UnitId.ShouldBeNull();
    }

    /// <summary>An authored RawPath carrying a unitId keys its own per-unit host name.</summary>
    [Fact]
    public async Task RawPath_WithUnitId_ResolvesPerUnitHostName()
    {
        const string rawPath = "cell/modbus/dev1/U7";
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}""";
        var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false));
        drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit7");
    }

    /// <summary>An authored RawPath without a unitId keys the driver-level unit host name.</summary>
    [Fact]
    public async Task RawPath_WithoutUnitId_KeysDriverDefaultUnit()
    {
        const string rawPath = "cell/modbus/dev1/U0";
        var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}""";
        var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false));
        drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit1");
    }
}
