package analytics

import (
	"testing"

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

// BuildViewDDL must be a pure function of its config: map iteration order in
// the DAG (topoSort seed queue, Layers bucketing) must never leak into the
// emitted SELECT list. Nondeterministic DDL churns view definitions between
// identical rebuilds and flaps the compiler-generation fingerprint, which
// would retrigger the startup view rebuild on every boot.
func TestBuildViewDDLDeterministicAcrossRuns(t *testing.T) {
	build := func() string {
		ddl, err := NewDSLViewBuilder().BuildViewDDL(ViewBuildConfig{
			ObjectName:    "SyntheticFormula",
			PhysicalTable: "synthetic_formula",
			TableAlias:    "t",
			BaseColumns:   []string{"Id", "A", "B", "C", "D"},
			FieldTypes: map[string]string{
				"A": string(constants.FieldTypeDouble),
				"B": string(constants.FieldTypeDouble),
				"C": string(constants.FieldTypeDouble),
				"D": string(constants.FieldTypeDouble),
			},
			// Four independent layer-0 formulas plus two layer-1 dependents:
			// enough same-layer members that unordered map iteration would be
			// overwhelmingly likely to reorder at least one pair per run.
			Formulas: []FormulaDefinition{
				{Name: "F1__c", Expression: "A + 1", ReturnType: string(constants.FieldTypeDouble)},
				{Name: "F2__c", Expression: "B + 1", ReturnType: string(constants.FieldTypeDouble)},
				{Name: "F3__c", Expression: "C + 1", ReturnType: string(constants.FieldTypeDouble)},
				{Name: "F4__c", Expression: "D + 1", ReturnType: string(constants.FieldTypeDouble)},
				{Name: "G1__c", Expression: "F1__c + F2__c", ReturnType: string(constants.FieldTypeDouble)},
				{Name: "G2__c", Expression: "F3__c + F4__c", ReturnType: string(constants.FieldTypeDouble)},
			},
		})
		if err != nil {
			t.Fatalf("BuildViewDDL() error = %v", err)
		}
		return ddl
	}

	first := build()
	for i := 0; i < 20; i++ {
		if got := build(); got != first {
			t.Fatalf("BuildViewDDL() output changed between identical runs (iteration %d):\nfirst:\n%s\n\ngot:\n%s", i, first, got)
		}
	}
}
