package catalogreconcile

import (
	"context"
	"encoding/json"
	"testing"

	consumerv1 "github.com/pingcap-inc/nexuscrm-contract/pkg/catalog/consumerv1"
	"github.com/pingcap-inc/nexuscrm-contract/pkg/seedrows"
)

type effectiveStandardActionReaderStub struct {
	definitions []seedrows.StandardActionDef
}

func (stub effectiveStandardActionReaderStub) GetEffectiveStandardActions(
	context.Context,
	[]string,
) ([]seedrows.StandardActionDef, error) {
	return stub.definitions, nil
}

func TestBuildEffectiveStandardActionComponentsPublishesTenantActionsAndPreservesAuthoredConfig(
	t *testing.T,
) {
	base := []byte(`[{"name":"convertLead","label":"Convert Lead","flowDeveloperName":"Std_ConvertLead","isAtomic":true,"config":{"rendererMode":"compact"}}]`)
	release := verifiedPlatformRelease(t, []platformReleaseComponentFixture{{
		kind: appReleaseInvocableActionComponentKind, businessKey: "bootstrap_standard_actions",
		behavior: base,
	}})
	components, err := buildEffectiveStandardActionComponents(
		context.Background(),
		effectiveStandardActionReaderStub{definitions: []seedrows.StandardActionDef{
			{Name: "convertLead", Label: "Convert Lead", FlowDeveloperName: "Std_ConvertLead", IsAtomic: true},
			{Name: "taskWeeklyUpdate", Label: "Weekly Update", FlowDeveloperName: "Std_CreateTaskActivity", IsAtomic: true},
		}},
		&release,
	)
	if err != nil {
		t.Fatal(err)
	}
	if len(components) != 1 ||
		components[0].ComponentKind != consumerv1.EffectiveStandardActionComponentKind ||
		components[0].BusinessKey != "bootstrap_standard_actions" {
		t.Fatalf("effective components = %#v", components)
	}
	var definitions []map[string]any
	if err := json.Unmarshal(components[0].CanonicalBehavior, &definitions); err != nil {
		t.Fatal(err)
	}
	if len(definitions) != 2 || definitions[1]["name"] != "taskWeeklyUpdate" {
		t.Fatalf("effective definitions = %#v", definitions)
	}
	config, ok := definitions[0]["config"].(map[string]any)
	if !ok || config["rendererMode"] != "compact" {
		t.Fatalf("authored config was not preserved: %#v", definitions[0])
	}
}
