package knowledgeqa

import (
	"reflect"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestAuthorizedRootJSONColumnPreservesStoredShape(t *testing.T) {
	roots := []AuthorizedRoot{{
		ID:              "root_1",
		KnowledgeBaseID: "kb_1",
		SourceID:        "src_1",
		RootHandleRef:   "handle_1",
		RootKind:        "repository",
		RepoRole:        "source",
		Revision:        "abc123",
		FreshnessStatus: "ready",
	}}
	raw, err := marshalAuthorizedRoots(roots)
	if err != nil {
		t.Fatal(err)
	}
	const expected = `[{"id":"root_1","knowledgeBaseId":"kb_1","sourceId":"src_1","rootHandleRef":"handle_1","rootKind":"repository","repoRole":"source","revision":"abc123","freshnessStatus":"ready"}]`
	if string(raw) != expected {
		t.Fatalf("marshalAuthorizedRoots() = %s, want %s", raw, expected)
	}
	decoded, err := unmarshalAuthorizedRoots(raw)
	if err != nil {
		t.Fatal(err)
	}
	if !reflect.DeepEqual(decoded, roots) {
		t.Fatalf("unmarshalAuthorizedRoots() = %#v, want %#v", decoded, roots)
	}
}

func TestUnmarshalAuthorizedRootsPreservesFrozenRepositoryRole(t *testing.T) {
	raw := []byte(`[{"id":"kqr_1","knowledgeBaseId":"kb_1","sourceId":"src_1","rootHandleRef":"kqr_1","rootKind":"repository","repoRole":"canonical","revision":"sha_1","freshnessStatus":"fresh"}]`)
	roots, err := unmarshalAuthorizedRoots(raw)
	require.NoError(t, err)
	require.Len(t, roots, 1)
	require.Equal(t, "canonical", roots[0].RepoRole)
}
