using Google.Protobuf;

namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;

/// <summary>
/// Shared helpers for building raw length-prefixed worker frames in tests.
/// Replaces the per-file <c>CreateFrame</c>/<c>WriteUInt32LittleEndian</c> copies
/// that were previously defined independently in WorkerFrameProtocolTests and
/// WorkerPipeSessionTests.
/// </summary>
internal static class WorkerFrameTestHelpers
{
    /// <summary>Builds a length-prefixed frame from a protobuf message.</summary>
    /// <param name="message">Message to serialize into the frame payload.</param>
    /// <returns>The length-prefixed frame bytes.</returns>
    public static byte[] CreateFrame(IMessage message)
    {
        return CreateFrame(message.ToByteArray());
    }

    /// <summary>Builds a length-prefixed frame from a raw payload.</summary>
    /// <param name="payload">Payload bytes to wrap in a frame.</param>
    /// <returns>The length-prefixed frame bytes.</returns>
    public static byte[] CreateFrame(byte[] payload)
    {
        byte[] frame = new byte[sizeof(uint) + payload.Length];
        WriteUInt32LittleEndian(frame, (uint)payload.Length);
        payload.CopyTo(frame, sizeof(uint));

        return frame;
    }

    /// <summary>Writes a little-endian unsigned 32-bit integer to the buffer head.</summary>
    /// <param name="buffer">Buffer to write into; must have at least four bytes.</param>
    /// <param name="value">Value to encode.</param>
    public static void WriteUInt32LittleEndian(
        byte[] buffer,
        uint value)
    {
        buffer[0] = (byte)value;
        buffer[1] = (byte)(value >> 8);
        buffer[2] = (byte)(value >> 16);
        buffer[3] = (byte)(value >> 24);
    }
}
