package controlplane

import (
	"os"
	"strings"
	"testing"
)

func TestSourcePackInstalledRowLookupStaysOutOfOpsRoot(t *testing.T) {
	rootSource := readSourcePackInstalledRowLookupSourceForStructureTest(t, "source_pack_ops.go")
	for _, forbidden := range []string{
		"func installedPackHasSourceIdentity(",
		"func sourceBackedPackFromInstalledRow(",
		"func sourceBackedPackFromInstalledRowWithComponentKindRegistrationSet(",
		"func sourceBackedPackFromInstalledRowWithFormulaBundles(",
		"func sourceBackedPackFromInstalledRowWithFormulaBundlesAndComponentKindRegistrationSet(",
		"func sourceIdentityMatches(",
		"func getInstalledPackRowByName(",
		"func getInstalledPackRowByNameForSourceRevisionAdvance(",
		"func queryInstalledPackRowByName(",
	} {
		if strings.Contains(rootSource, forbidden) {
			t.Fatalf("source_pack_ops.go still owns installed row lookup surface %q", forbidden)
		}
	}

	lookupSource := readSourcePackInstalledRowLookupSourceForStructureTest(t, "source_pack_installed_row_lookup.go")
	for _, want := range []string{
		"func installedPackHasSourceIdentity(",
		"func sourceBackedPackFromInstalledRow(",
		"func sourceBackedPackFromInstalledRowWithComponentKindRegistrationSet(",
		"func sourceBackedPackFromInstalledRowWithFormulaBundles(",
		"func sourceBackedPackFromInstalledRowWithFormulaBundlesAndComponentKindRegistrationSet(",
		"func sourceIdentityMatches(",
		"func getInstalledPackRowByName(",
		"func getInstalledPackRowByNameForSourceRevisionAdvance(",
		"func queryInstalledPackRowByName(",
		`"Id",`,
		`"COALESCE(PackInstallId, '')"`,
		"dest = []any{&row.ID, &row.Name, &row.PackInstallID}",
		"ResolveInstalledSourceBackedPackForInstalledRowAtSourceRevisionWithPackSourceOptions",
		"ResolveInstalledSourceBackedPackForInstalledRowAtSourceRevisionWithPackSourceOptionsAndComponentKindRegistrationSet",
		"ResolveInstalledSourceBackedPackForInstalledRowAtSourceRevisionWithPackSourceOptionsAndFormulaBundlesAndComponentKindRegistrationSet",
	} {
		if !strings.Contains(lookupSource, want) {
			t.Fatalf("source_pack_installed_row_lookup.go missing installed row lookup surface %q", want)
		}
	}
}

func readSourcePackInstalledRowLookupSourceForStructureTest(t *testing.T, path string) string {
	t.Helper()
	raw, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read %s: %v", path, err)
	}
	return string(raw)
}
