package records

import (
	"strings"
	"testing"
)

func TestGuardedUpdatePreservesParentBeforeChildLockOrder(t *testing.T) {
	updateSrc := readRecordsSourceForRawAccessStructure(t, "persistence_update.go")
	parentPrelock := strings.Index(updateSrc, "ps.prelockInitialUpdateParents(")
	childLock := strings.Index(updateSrc, "lockedGuardRecord, err = ps.loadAndValidateAccessWithAuthorization(")
	guard := strings.Index(updateSrc, "guard(txCtx, cloneSObject(lockedGuardRecord))")
	prepare := strings.Index(updateSrc, "ps.prepareUpdateBeforeSaveFromLockedRecord(")
	beforeUpdate := strings.Index(updateSrc, "ps.publishRecordEvent(txCtx, events.RecordBeforeUpdate")
	if parentPrelock < 0 || childLock < 0 || guard < 0 || prepare < 0 || beforeUpdate < 0 {
		t.Fatalf("guarded Update stages missing: parent=%d child=%d guard=%d prepare=%d beforeUpdate=%d", parentPrelock, childLock, guard, prepare, beforeUpdate)
	}
	if !(parentPrelock < childLock && childLock < guard && guard < prepare && prepare < beforeUpdate) {
		t.Fatalf("guarded Update stage order changed: parent=%d child=%d guard=%d prepare=%d beforeUpdate=%d", parentPrelock, childLock, guard, prepare, beforeUpdate)
	}
}
