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

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

/// <summary>
///     Unit tests for the Modbus-exception-code → OPC UA StatusCode mapping added in PR 52.
///     Before PR 52 every server exception + every transport failure collapsed to
///     BadInternalError (0x80020000), which made field diagnosis "is this a bad tag or a bad
///     driver?" impossible. These tests lock in the translation table documented on
///     <see cref="ModbusDriver.MapModbusExceptionToStatus"/>.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ModbusExceptionMapperTests
{
    /// <summary>Verifies that Modbus exception codes map to informative OPC UA status codes.</summary>
    /// <param name="code">Modbus exception code.</param>
    /// <param name="expected">Expected OPC UA status code.</param>
    [Theory]
    [InlineData((byte)0x01, 0x803D0000u)] // Illegal Function → BadNotSupported
    [InlineData((byte)0x02, 0x803C0000u)] // Illegal Data Address → BadOutOfRange
    [InlineData((byte)0x03, 0x803C0000u)] // Illegal Data Value → BadOutOfRange
    [InlineData((byte)0x04, 0x808B0000u)] // Server Failure → BadDeviceFailure (Driver.Cli.Common-007)
    [InlineData((byte)0x05, 0x808B0000u)] // Acknowledge (long op) → BadDeviceFailure
    [InlineData((byte)0x06, 0x808B0000u)] // Server Busy → BadDeviceFailure
    [InlineData((byte)0x0A, 0x80050000u)] // Gateway path unavailable → BadCommunicationError
    [InlineData((byte)0x0B, 0x80050000u)] // Gateway target failed to respond → BadCommunicationError
    [InlineData((byte)0xFF, 0x80020000u)] // Unknown code → BadInternalError fallback
    public void MapModbusExceptionToStatus_returns_informative_status(byte code, uint expected)
        => ModbusDriver.MapModbusExceptionToStatus(code).ShouldBe(expected);

    /// <summary>Test transport that raises Modbus exceptions on send.</summary>
    private sealed class ExceptionRaisingTransport(byte exceptionCode) : IModbusTransport
    {
        /// <summary>Completes immediately.</summary>
        /// <param name="ct">Cancellation token.</param>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;

        /// <summary>Returns a failed task with a Modbus exception.</summary>
        /// <param name="unitId">Modbus unit identifier.</param>
        /// <param name="pdu">Protocol data unit to send.</param>
        /// <param name="ct">Cancellation token.</param>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
            => Task.FromException<byte[]>(new ModbusException(pdu[0], exceptionCode, $"fc={pdu[0]} code={exceptionCode}"));

        /// <summary>Completes immediately.</summary>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    /// <summary>Verifies that exception 0x02 surfaces as BadOutOfRange, not BadInternalError.</summary>
    [Fact]
    public async Task Read_surface_exception_02_as_BadOutOfRange_not_BadInternalError()
    {
        var transport = new ExceptionRaisingTransport(exceptionCode: 0x02);
        var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
        await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
        await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);

        var results = await drv.ReadAsync(["T"], TestContext.Current.CancellationToken);
        results[0].StatusCode.ShouldBe(0x803C0000u, "FC03 at an unmapped register must bubble out as BadOutOfRange so operators can spot a bad tag config");
    }

    /// <summary>Verifies that exception 0x04 surfaces as BadDeviceFailure.</summary>
    [Fact]
    public async Task Write_surface_exception_04_as_BadDeviceFailure()
    {
        var transport = new ExceptionRaisingTransport(exceptionCode: 0x04);
        var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
        await using var drv = new ModbusDriver(opts, "modbus-1", _ => transport);
        await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);

        var writes = await drv.WriteAsync(
            [new WriteRequest("T", (short)42)],
            TestContext.Current.CancellationToken);

        writes[0].StatusCode.ShouldBe(0x808B0000u, "FC06 returning exception 04 (CPU in PROGRAM mode) maps to BadDeviceFailure");
    }

    /// <summary>Test transport that raises non-Modbus exceptions on send.</summary>
    private sealed class NonModbusFailureTransport : IModbusTransport
    {
        /// <summary>Completes immediately.</summary>
        /// <param name="ct">Cancellation token.</param>
        public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;

        /// <summary>Returns a failed task with a non-Modbus exception.</summary>
        /// <param name="unitId">Modbus unit identifier.</param>
        /// <param name="pdu">Protocol data unit to send.</param>
        /// <param name="ct">Cancellation token.</param>
        public Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct)
            => Task.FromException<byte[]>(new EndOfStreamException("socket closed mid-response"));

        /// <summary>Completes immediately.</summary>
        public ValueTask DisposeAsync() => ValueTask.CompletedTask;
    }

    /// <summary>Verifies that non-Modbus transport failures surface as BadCommunicationError.</summary>
    [Fact]
    public async Task Read_non_modbus_failure_maps_to_BadCommunicationError_not_BadInternalError()
    {
        // Socket drop / timeout / malformed frame → transport-layer failure. Should surface
        // distinctly from tag-level faults so operators know to check the network, not the config.
        var tag = new ModbusTagDefinition("T", ModbusRegion.HoldingRegisters, 0, ModbusDataType.Int16);
        var opts = new ModbusDriverOptions { Host = "fake", RawTags = ModbusRawTags.Entries([tag]), Probe = new ModbusProbeOptions { Enabled = false } };
        await using var drv = new ModbusDriver(opts, "modbus-1", _ => new NonModbusFailureTransport());
        await drv.InitializeAsync("{}", TestContext.Current.CancellationToken);

        var results = await drv.ReadAsync(["T"], TestContext.Current.CancellationToken);
        results[0].StatusCode.ShouldBe(0x80050000u);
    }
}
