package catalogreconcile

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

	"github.com/nexuscrm/shared/pkg/models"
)

type effectiveObjectActionReaderStub struct {
	actions map[string][]*models.ActionMetadata
}

func (stub effectiveObjectActionReaderStub) GetAllActions(_ context.Context) ([]*models.ActionMetadata, error) {
	var result []*models.ActionMetadata
	for _, actions := range stub.actions {
		result = append(result, actions...)
	}
	return result, nil
}

func TestBuildEffectiveObjectActionComponentsPublishesDeterministicScopedActions(t *testing.T) {
	target := "ContractDocument"
	components, err := buildEffectiveObjectActionComponents(
		context.Background(),
		effectiveObjectActionReaderStub{actions: map[string][]*models.ActionMetadata{
			"Contract": {
				{ID: "action-upload", ObjectAPIName: "Contract", Name: "UploadArchivedContract", Label: "Upload Archived Contract", Type: "UploadFileUpdateRecord", TargetObject: &target, Config: map[string]any{"visibilityCondition": "record.Status == 'Approved'"}},
				{ID: "action-owner", ObjectAPIName: "Contract", Name: "ChangeOwner", Label: "Change Owner", Type: "ChangeOwner"},
			},
		}},
		[]string{"Contract"},
	)
	if err != nil {
		t.Fatal(err)
	}
	if len(components) != 1 || components[0].ComponentKind != EffectiveObjectActionComponentKind || components[0].BusinessKey != "Contract" {
		t.Fatalf("components = %#v", components)
	}
	var document effectiveObjectActionDocument
	if err := json.Unmarshal(components[0].CanonicalBehavior, &document); err != nil {
		t.Fatal(err)
	}
	if len(document.Actions) != 2 || document.Actions[0].Name != "ChangeOwner" || document.Actions[1].Name != "UploadArchivedContract" || document.Actions[1].TargetObject != target {
		t.Fatalf("document = %#v", document)
	}
}
