{-# LANGUAGE OverloadedStrings #-}

module Hsm.Core.Message
  ( message
  , topic
  , body
  ) where

import Data.Binary (Binary, decode, encode)
import Data.ByteString (ByteString, fromStrict, toStrict)
import Data.ByteString.Char8 qualified as B (breakSubstring, drop, length)
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)

sep :: ByteString
sep = "//"

message :: Binary a => Text -> a -> ByteString
message t b = encodeUtf8 t <> sep <> toStrict (encode b)

topic :: ByteString -> Text
topic = decodeUtf8 . fst . B.breakSubstring sep

body :: Binary a => ByteString -> a
body = decode . fromStrict . B.drop (B.length sep) . snd . B.breakSubstring sep