package commandv1

import (
	"context"
	"testing"
	"time"

	common "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/commonv1"
)

func TestCommandAcceptanceIsVersionedAndRequestCorrelated(t *testing.T) {
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second))
	defer cancel()
	request := Request{CommandID: "command-1", IdempotencyKey: "request-1", CommandKind: "runtime.flow.execute",
		PayloadFormatVersion: 1, Payload: []byte{0x00, 0x01}}
	request.PayloadDigest = ComputePayloadDigest(request.Payload)
	if err := ValidateRequest(ctx, request); err != nil {
		t.Fatalf("ValidateRequest() error = %v", err)
	}
	response := Response{CommandID: request.CommandID,
		Receipts: common.Receipts{ProtocolVersion: "1.0", CapabilityVersion: CapabilityName}}
	if err := ValidateResponse(request, response); err != nil {
		t.Fatalf("ValidateResponse() error = %v", err)
	}
	response.CommandID = "command-2"
	if ValidateResponse(request, response) == nil {
		t.Fatal("response for another command was accepted")
	}
	request.PayloadFormatVersion = 0
	if ValidateRequest(ctx, request) == nil {
		t.Fatal("unversioned command payload was accepted")
	}
	request.PayloadFormatVersion = 1
	request.Payload[0] = 0xff
	if ValidateRequest(ctx, request) == nil {
		t.Fatal("payload whose digest no longer matched was accepted")
	}
}

func TestValidCommandKindUsesTheAcceptanceIdentifierGrammar(t *testing.T) {
	for _, value := range []string{
		"runtime.flow.execute",
		"_runtime/flow:v1",
	} {
		if !ValidCommandKind(value) {
			t.Fatalf("ValidCommandKind(%q) = false", value)
		}
	}
	for _, value := range []string{"", "runtime flow execute", "1runtime"} {
		if ValidCommandKind(value) {
			t.Fatalf("ValidCommandKind(%q) = true", value)
		}
	}
}
