package dispatcher

import (
	"bytes"
	"testing"
	"time"
)

func TestSplitAndReassembleEnvelope(t *testing.T) {
	encoded := bytes.Repeat([]byte("yamn-envelope\n"), 900)
	payloads, err := SplitEnvelope(encoded)
	if err != nil {
		t.Fatal(err)
	}
	if len(payloads) < 2 {
		t.Fatal("expected multiple frames")
	}

	reassembler := NewReassembler(time.Minute)
	var result []byte
	for _, payload := range payloads {
		if len(payload) > MaxSphinxPayload {
			t.Fatalf("payload exceeds limit: %d", len(payload))
		}
		frame, err := DecodeFrame(payload)
		if err != nil {
			t.Fatal(err)
		}
		assembled, complete, err := reassembler.Add(frame)
		if err != nil {
			t.Fatal(err)
		}
		if complete {
			result = assembled
		}
	}
	if !bytes.Equal(result, encoded) {
		t.Fatal("reassembled envelope differs")
	}
}

func TestDecodeFrameRejectsOversizedPayload(t *testing.T) {
	if _, err := DecodeFrame(make([]byte, MaxSphinxPayload+1)); err == nil {
		t.Fatal("expected oversized payload rejection")
	}
}
