package mloco

import (
	"bytes"
	"testing"
)

func TestPacketRoundTrip(t *testing.T) {
	body := encodeBSONDocument(map[string]any{"userId": int64(7)})
	p := packet{
		header: packetHeader{
			ID:       42,
			Method:   "LOGINLIST",
			bodyType: 1,
			bodyLen:  uint32(len(body)),
		},
		body: body,
	}
	raw := p.encode()
	if len(raw) != packetHeaderSize+len(body) {
		t.Fatalf("wrong encoded length: %d", len(raw))
	}
	got, err := readPacket(bytes.NewReader(raw))
	if err != nil {
		t.Fatalf("read failed: %v", err)
	}
	if got.header.ID != 42 {
		t.Errorf("id = %d", got.header.ID)
	}
	if got.header.Method != "LOGINLIST" {
		t.Errorf("method = %q", got.header.Method)
	}
	if !bytes.Equal(got.body, body) {
		t.Errorf("body mismatch")
	}
}

func TestPacketHeaderBuf(t *testing.T) {
	h := packetHeader{ID: 1, Method: "GETCONF", bodyType: 0}
	parsed, err := parsePacketHeader(h.encode())
	if err != nil {
		t.Fatalf("parse: %v", err)
	}
	if parsed.Method != "GETCONF" {
		t.Errorf("method = %q", parsed.Method)
	}
}
