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

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

/// <summary>
///     #142 multi-unit-ID gateway support: per-tag UnitId override + IPerCallHostResolver +
///     wire-level routing of UnitId in the MBAP header per-PDU.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusMultiUnitTests
{
    private sealed class UnitCapturingTransport : IModbusTransport
    {
        public readonly List<byte> SeenUnitIds = new();
        /// <summary>Connects to the transport.</summary>
        /// <param name="ct">Token to cancel the connection.</param>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
        /// <summary>Sends a Modbus PDU and returns a response.</summary>
        /// <param name="unitId">The Modbus unit ID for the request.</param>
        /// <param name="pdu">The protocol data unit to send.</param>
        /// <param name="ct">Token to cancel the operation.</param>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
        {
            SeenUnitIds.Add(unitId);
            switch (pdu[0])
            {
                case 0x03: case 0x04:
                {
                    var qty = (ushort)((pdu[3] << 8) | pdu[4]);
                    var resp = new byte[2 + qty * 2];
                    resp[0] = pdu[0]; resp[1] = (byte)(qty * 2);
                    return Task.FromResult(resp);
                }
                default: return Task.FromResult(new byte[] { pdu[0], 0, 0 });
            }
        }
        /// <summary>Disposes the transport resources.</summary>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    /// <summary>Verifies that per-tag UnitId routes reads to the correct slave.</summary>
    [Fact]
    public async Task PerTag_UnitId_Routes_To_Correct_Slave_In_MBAP()
    {
        var fake = new UnitCapturingTransport();
        var tagSlave1 = new ModbusTagDefinition("S1Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 1);
        var tagSlave5 = new ModbusTagDefinition("S5Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 5);
        var opts = new ModbusDriverOptions { Host = "f", UnitId = 99, RawTags = ModbusRawTags.Entries([tagSlave1, tagSlave5]),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(["S1Temp", "S5Temp"], CancellationToken.None);

        // Two reads: one for slave 1, one for slave 5. Driver-level UnitId=99 must NOT appear.
        fake.SeenUnitIds.ShouldContain((byte)1);
        fake.SeenUnitIds.ShouldContain((byte)5);
        fake.SeenUnitIds.ShouldNotContain((byte)99);
    }

    /// <summary>Verifies that tags without UnitId override use the driver-level UnitId.</summary>
    [Fact]
    public async Task Tag_Without_UnitId_Falls_Back_To_DriverLevel()
    {
        var fake = new UnitCapturingTransport();
        var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16); // no UnitId override
        var opts = new ModbusDriverOptions { Host = "f", UnitId = 7, RawTags = ModbusRawTags.Entries([tag]),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        await drv.ReadAsync(["T"], CancellationToken.None);

        fake.SeenUnitIds.ShouldContain((byte)7);
    }

    /// <summary>Verifies that IPerCallHostResolver returns per-slave host strings.</summary>
    [Fact]
    public async Task IPerCallHostResolver_Returns_Per_Slave_Host_String()
    {
        var fake = new UnitCapturingTransport();
        var t1 = new ModbusTagDefinition("S1Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 1);
        var t5 = new ModbusTagDefinition("S5Temp", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16, UnitId: 5);
        var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, RawTags = ModbusRawTags.Entries([t1, t5]),
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        // The pipeline keys breakers on these strings; distinct slave IDs must produce distinct
        // host strings so per-PLC isolation works.
        var resolver = (IPerCallHostResolver)drv;
        resolver.ResolveHost("S1Temp").ShouldBe("10.1.2.3:502/unit1");
        resolver.ResolveHost("S5Temp").ShouldBe("10.1.2.3:502/unit5");
        resolver.ResolveHost("S1Temp").ShouldNotBe(resolver.ResolveHost("S5Temp"));
    }

    /// <summary>Verifies that IPerCallHostResolver falls back to hostname for unknown tags.</summary>
    [Fact]
    public async Task IPerCallHostResolver_Unknown_Tag_Falls_Back_To_HostName()
    {
        var fake = new UnitCapturingTransport();
        var opts = new ModbusDriverOptions { Host = "10.1.2.3", Port = 502, RawTags = [],
            Probe = new ModbusProbeOptions { Enabled = false } };
        var drv = new ModbusDriver(opts, "m1", _ => fake);
        await drv.InitializeAsync("{}", CancellationToken.None);

        var resolver = (IPerCallHostResolver)drv;
        resolver.ResolveHost("never-defined").ShouldBe("10.1.2.3:502");
    }
}
