package nym

import "testing"

func TestParseRecipient(t *testing.T) {
	// Real nymdrop-inbox address (see project session.md).
	addr := "5xme8W448FjvSG69GaNWNkSwYpurgzmLrooPMt6XWThU.GpKLJHB2oiSqRsG5u55t4h2D25tA7BNSfvCQbfup3j1k@6mMs1GQkDRa7rPPtzG9vkFscmEBmAvQX4zjLSoaDg9Wa"

	got, err := ParseRecipient(addr)
	if err != nil {
		t.Fatalf("parseRecipient: %v", err)
	}
	if len(got) != RecipientLen {
		t.Fatalf("expected %d bytes, got %d", RecipientLen, len(got))
	}
}

func TestParseRecipientRustTestVector(t *testing.T) {
	// Same address used in nym-client's own Rust unit tests
	// (websocket-requests/src/requests.rs: send_request_serialization_works).
	addr := "CytBseW6yFXUMzz4SGAKdNLGR7q3sJLLYxyBGvutNEQV.4QXYyEVc5fUDjmmi8PrHN9tdUFV4PCvSJE1278cHyvoe@4sBbL1ngf1vtNqykydQKTFh26sQCw888GpUqvPvyNB4f"

	got, err := ParseRecipient(addr)
	if err != nil {
		t.Fatalf("parseRecipient: %v", err)
	}
	if len(got) != RecipientLen {
		t.Fatalf("expected %d bytes, got %d", RecipientLen, len(got))
	}
}

func TestParseRecipientMalformed(t *testing.T) {
	cases := []string{
		"",
		"no-at-sign",
		"a@b@c",
		"nodot@gateway",
		"id.enc@0OIl", // invalid base58 chars
	}
	for _, addr := range cases {
		if _, err := ParseRecipient(addr); err == nil {
			t.Errorf("ParseRecipient(%q): expected error, got none", addr)
		}
	}
}

func TestMakeSendRequestLayout(t *testing.T) {
	c := &Client{recipient: make([]byte, RecipientLen)}
	for i := range c.recipient {
		c.recipient[i] = byte(i)
	}
	payload := []byte("hello mixnet")

	req := make([]byte, 0, 1+len(c.recipient)+8+8+len(payload))
	req = append(req, ReqSend)
	req = append(req, c.recipient...)
	req = append(req, 0, 0, 0, 0, 0, 0, 0, 0) // connection_id = 0
	req = append(req, 0, 0, 0, 0, 0, 0, 0, byte(len(payload)))
	req = append(req, payload...)

	wantLen := 1 + RecipientLen + 8 + 8 + len(payload)
	if len(req) != wantLen {
		t.Fatalf("expected length %d, got %d", wantLen, len(req))
	}
	if req[0] != 0x00 {
		t.Fatalf("expected tag 0x00, got 0x%02x", req[0])
	}
}
