package packs

import (
	"testing"
)

func TestCompatibilityDeclarationsFromObjectSpecPayloadsBuildsObjectIdentities(t *testing.T) {
	payload := []byte(`[
		{"apiName":"Issue","keyPrefix":"500","category":"jira"},
		{"apiName":"Project","category":"jira"}
	]`)
	decls, err := compatibilityDeclarationsFromObjectSpecPayloads([][]byte{payload}, "jira-pack")
	if err != nil {
		t.Fatalf("compatibilityDeclarationsFromObjectSpecPayloads: %v", err)
	}

	gotPrefix, ok := keyPrefixForObjectFromDeclarations(decls, "Issue")
	if !ok || gotPrefix != "500" {
		t.Fatalf("keyPrefixForObjectFromDeclarations(Issue) = (%q, %v), want (500, true)", gotPrefix, ok)
	}
	if gotPrefix, ok := keyPrefixForObjectFromDeclarations(decls, "Project"); !ok || gotPrefix != "" {
		t.Fatalf("keyPrefixForObjectFromDeclarations(Project) = (%q, %v), want (empty, true)", gotPrefix, ok)
	}
}

func TestCompatibilityDeclarationsFromObjectSpecPayloadsRejectsConflictingRelationships(t *testing.T) {
	payload := []byte(`[
		{
			"apiName":"Issue",
			"category":"jira",
			"fields":[
				{"apiName":"ParentId","relationshipName":"Parent","referenceTo":["Issue"]},
				{"apiName":"EpicId","relationshipName":"Parent","referenceTo":["Epic"]}
			]
		}
	]`)
	if _, err := compatibilityDeclarationsFromObjectSpecPayloads([][]byte{payload}, "jira-spec"); err == nil {
		t.Fatal("expected conflicting relationship declarations to fail")
	}
}

func TestCompatibilityDeclarationsFromObjectSpecPayloadsRejectsDuplicateKeyPrefixes(t *testing.T) {
	payload := []byte(`[
		{"apiName":"Issue","keyPrefix":"500","category":"jira"},
		{"apiName":"Bug","keyPrefix":"500","category":"jira"}
	]`)
	if _, err := compatibilityDeclarationsFromObjectSpecPayloads([][]byte{payload}, "jira-spec"); err == nil {
		t.Fatal("expected duplicate key prefix declarations to fail")
	}
}
