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

/// <summary>
///     Abstraction over the Modbus TCP socket. Takes a <c>PDU</c> (function code + data, excluding
///     the 7-byte MBAP header) and returns the response PDU — the transport owns transaction-id
///     pairing, framing, and socket I/O. Tests supply in-memory fakes.
/// </summary>
public interface IModbusTransport : IAsyncDisposable
{
    /// <summary>Establishes a connection to the Modbus server.</summary>
    /// <param name="ct">A cancellation token to observe for cancellation.</param>
    /// <returns>A task representing the asynchronous connection operation.</returns>
    Task ConnectAsync(CancellationToken ct);

    /// <summary>
    ///     Send a Modbus PDU (function code + function-specific data) and read the response PDU.
    ///     Throws <see cref="ModbusException"/> when the server returns an exception PDU
    ///     (function code + 0x80 + exception code).
    /// </summary>
    /// <param name="unitId">The Modbus unit identifier (slave address).</param>
    /// <param name="pdu">The protocol data unit (function code and data) to send.</param>
    /// <param name="ct">A cancellation token to observe for cancellation.</param>
    /// <returns>A task representing the asynchronous send operation that returns the response PDU.</returns>
    Task<byte[]> SendAsync(byte unitId, byte[] pdu, CancellationToken ct);
}

/// <summary>Represents a Modbus protocol exception.</summary>
public sealed class ModbusException(byte functionCode, byte exceptionCode, string message)
    : Exception(message)
{
    /// <summary>Gets the Modbus function code that caused the exception.</summary>
    public byte FunctionCode { get; } = functionCode;

    /// <summary>Gets the Modbus exception code.</summary>
    public byte ExceptionCode { get; } = exceptionCode;
}
