package dispatcher

import (
	"fmt"

	"github.com/fxamacker/cbor/v2"
)

func EncodeEnvelope(envelope Envelope) ([]byte, error) {
	encoded, err := cbor.Marshal(envelope)
	if err != nil {
		return nil, fmt.Errorf("encode envelope: %w", err)
	}
	if len(encoded) > MaxEnvelopeBytes {
		return nil, fmt.Errorf("encoded envelope is too large")
	}
	return encoded, nil
}

func DecodeEnvelope(encoded []byte) (Envelope, error) {
	if len(encoded) == 0 || len(encoded) > MaxEnvelopeBytes {
		return Envelope{}, fmt.Errorf("invalid encoded envelope size")
	}
	var envelope Envelope
	if err := cbor.Unmarshal(encoded, &envelope); err != nil {
		return Envelope{}, fmt.Errorf("decode envelope: %w", err)
	}
	return envelope, nil
}
