#include "message_protocol/MessageHeader.hpp"

#include <catch2/catch_test_macros.hpp>

#include <array>

using namespace tw::msg;

TEST_CASE("Header survives a round trip", "[message_header]") {
    std::array<std::byte, MessageHeader::SIZE> buffer{};

    MessageHeader{ 42, 7 }.encode(buffer);

    auto decoded = MessageHeader::decode(buffer);

    REQUIRE(decoded.has_value());
    REQUIRE(decoded->type == 42);
    REQUIRE(decoded->seq == 7);
}

TEST_CASE("Header defaults to expecting no reply", "[message_header]") {
    std::array<std::byte, MessageHeader::SIZE> buffer{};

    MessageHeader{ 3 }.encode(buffer);

    auto decoded = MessageHeader::decode(buffer);

    REQUIRE(decoded.has_value());
    REQUIRE(decoded->seq == MessageHeader::SEQ_NONE);
}

TEST_CASE("Decoding a message shorter than a header fails", "[message_header]") {
    std::array<std::byte, MessageHeader::SIZE - 1> buffer{};

    REQUIRE_FALSE(MessageHeader::decode(buffer).has_value());
}

TEST_CASE("Encoding only writes the header", "[message_header]") {
    std::array<std::byte, MessageHeader::SIZE + 4> buffer{};
    buffer[MessageHeader::SIZE] = std::byte{ 0xAB };

    MessageHeader{ 1, 2 }.encode(buffer);

    REQUIRE(buffer[MessageHeader::SIZE] == std::byte{ 0xAB });
}
