package persistence

import (
	"encoding/json"
	"strings"
	"testing"

	applicationresultsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/applicationresultv1"
	flowcommandsemanticv3 "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/flowcommandv3"
)

var runtimePlatformApplicationResultReadinessColumns = []string{
	"Id", "State", "Payload", "ResultPayload",
}

func runtimePlatformApplicationResultTestScope() RuntimeWorkScope {
	return RuntimeWorkScope{
		OrgID:               "org-1",
		AppInstallationID:   "installation-1",
		RuntimeCapabilityID: "runtime.flow.execute.v3",
	}
}

func mustRuntimePlatformApplicationResultV3Payload(t *testing.T) []byte {
	t.Helper()
	inputs := []byte(`{"record":{"id":"record-1"}}`)
	inputDigest, err := flowcommandsemanticv3.ComputeInputDigest(
		inputs,
		flowcommandsemanticv3.AllowExternalEffects,
	)
	if err != nil {
		t.Fatal(err)
	}
	payload, err := flowcommandsemanticv3.Encode(flowcommandsemanticv3.Payload{
		ExecutionRef: applicationresultsemantic.ExecutionRef{
			ExecutionID:        "execution-1",
			PackGenerationID:   "pack-generation-1",
			ServingEpochDigest: "sha256:" + strings.Repeat("a", 64),
			DefinitionRef:      "flow.neutral",
			DefinitionVersion:  "flow-version-1",
			InputDigest:        inputDigest,
		},
		CanonicalInputs:     inputs,
		ExternalEffectsMode: flowcommandsemanticv3.AllowExternalEffects,
	})
	if err != nil {
		t.Fatal(err)
	}
	return payload
}

func mustRuntimePlatformApplicationResultCompletion(
	t *testing.T,
	outcome applicationresultsemantic.Outcome,
	failureCode applicationresultsemantic.FailureCode,
) string {
	t.Helper()
	encoded, err := encodeRuntimePlatformCommandApplicationCompletion(
		RuntimePlatformCommandApplicationCompletion{
			Outcome:     outcome,
			FailureCode: failureCode,
			Body:        json.RawMessage(`{"executionId":"flow-execution-1"}`),
		},
	)
	if err != nil {
		t.Fatal(err)
	}
	return encodeRuntimePlatformCommandResult(encoded)
}
