package serviceactor

import (
	"fmt"
	"strings"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestValidateInternalHandlerResultJSONBoundsObjectPayloads(t *testing.T) {
	t.Parallel()

	require.NoError(t, validateInternalHandlerResultJSON(nil))
	require.NoError(t, validateInternalHandlerResultJSON([]byte(`{"status":"ok","sequence":9007199254740993}`)))

	for name, payload := range map[string][]byte{
		"malformed":       []byte(`{"status":`),
		"multiple":        []byte(`{} {}`),
		"non object":      []byte(`["ok"]`),
		"blank key":       []byte(`{" ":true}`),
		"oversized bytes": []byte(fmt.Sprintf(`{"value":%q}`, strings.Repeat("x", internalHandlerMaxResultBytes))),
	} {
		payload := payload
		t.Run(name, func(t *testing.T) {
			t.Parallel()
			require.ErrorIs(t, validateInternalHandlerResultJSON(payload), ErrBadRequest)
		})
	}

	deep := `true`
	for index := 0; index <= internalHandlerMaxResultValueDepth; index++ {
		deep = `{"child":` + deep + `}`
	}
	require.ErrorIs(t, validateInternalHandlerResultJSON([]byte(deep)), ErrBadRequest)

	values := make([]string, internalHandlerMaxResultValueCount)
	for index := range values {
		values[index] = "true"
	}
	require.ErrorIs(t, validateInternalHandlerResultJSON([]byte(`{"values":[`+strings.Join(values, ",")+`]}`)), ErrBadRequest)
}
