package runtimeapi

import (
	"strings"
	"testing"

	"github.com/nexuscrm/metadata/catalogsnapshot"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/models"
)

func TestOpenCommandConsumerRuntimeViewRequiresExactCompatibleSnapshot(
	t *testing.T,
) {
	revision := catalogsnapshot.CatalogRevision(17)
	input := catalogsnapshot.CompileInput{
		OrgID: "org-test",
		Lineage: catalogsnapshot.Lineage{
			CatalogRevision:  revision,
			SchemaGeneration: 8,
			EngineGeneration: 9,
		},
		Objects: []catalogsnapshot.ObjectInput{{
			CatalogRevision: revision,
			Metadata: &models.ObjectMetadata{
				ID: "object-work-item", APIName: "WorkItem",
				Label: "Work Item", PluralLabel: "Work Items",
				SharingModel: constants.SharingModelPublicReadWrite,
				Fields: []models.FieldMetadata{{
					ID: "field-work-item-id", APIName: constants.FieldID,
					Label: "ID", Type: constants.FieldTypeString,
					PhysicalName: "id", IsSystem: true,
				}},
			},
		}},
		CommandRegistrations: []catalogsnapshot.CommandRegistrationInput{{
			CatalogRevision:   revision,
			ComponentID:       "component.command.flow",
			DefinitionVersion: "1",
			ContentDigest: catalogsnapshot.Digest(
				"sha256:" + strings.Repeat("a", 64),
			),
			CommandKind:          "runtime.flow.execute",
			PayloadFormatVersion: 1,
			ExecutionBindings: []catalogsnapshot.CommandExecutionBinding{{
				AuthorizedWorkloadID: "integration-service",
				DefinitionRef:        "flow.integration-ingress",
				DefinitionVersion:    "flow-version-1",
				ContextNamespace:     "connector.test",
			}},
		}},
		Projections: []catalogsnapshot.RuntimeProjectionInput{{
			CatalogRevision:        revision,
			AppInstallationID:      "installation-test",
			CapabilityID:           "runtime.commands.accept.v1",
			Profile:                catalogsnapshot.ProjectionCommandAcceptanceV1,
			DefinitionComponentIDs: []string{"component.command.flow"},
		}},
	}
	artifact, err := catalogsnapshot.CompileCatalogSnapshot(input)
	if err != nil {
		t.Fatal(err)
	}
	store, err := catalogsnapshot.NewDirectoryStore(t.TempDir())
	if err != nil {
		t.Fatal(err)
	}
	if err := store.Put(t.Context(), artifact); err != nil {
		t.Fatal(err)
	}
	compatibility := catalogsnapshot.Compatibility{
		SchemaGeneration: 8,
		EngineGeneration: 9,
	}
	view, err := newServingArtifactSet(store).consumerView(
		t.Context(),
		artifact.Digest(),
		"org-test",
		"installation-test",
		"runtime.commands.accept.v1",
		compatibility,
	)
	if err != nil {
		t.Fatal(err)
	}
	if _, ok := view.CommandExecutionContext(
		"runtime.flow.execute",
		1,
		"integration-service",
		"flow.integration-ingress",
		"flow-version-1",
	); !ok {
		t.Fatal("exact command execution authority was not projected")
	}

	if _, err := newServingArtifactSet(store).consumerView(
		t.Context(),
		artifact.Digest(),
		"other-org",
		"installation-test",
		"runtime.commands.accept.v1",
		compatibility,
	); err == nil {
		t.Fatal("wrong-org command snapshot was accepted")
	}
	compatibility.EngineGeneration++
	if _, err := newServingArtifactSet(store).consumerView(
		t.Context(),
		artifact.Digest(),
		"org-test",
		"installation-test",
		"runtime.commands.accept.v1",
		compatibility,
	); err == nil {
		t.Fatal("stale engine generation was accepted")
	}
}
