package controlplane

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

// TestApplyOptionsMirrorsCoverDeferFlag guards the whole class of "new
// InstallPackOptions -> packs.ApplyOptions mirror site forgets a field":
// every non-test construction that mirrors install options (identified by
// copying SkipPolymorphicDiscriminatorBackfill) must either mirror
// DeferFormulaViewRebuild too or carry an explicit deliberate-omission
// comment naming the field. Review round 2 of the defer option found exactly
// this hole in the source-revision orchestrator.
func TestApplyOptionsMirrorsCoverDeferFlag(t *testing.T) {
	literal := regexp.MustCompile(`(?s)packs\.ApplyOptions\{.*?\}`)
	checked := 0
	walkErr := filepath.WalkDir(".", func(path string, entry os.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() {
			if strings.HasPrefix(entry.Name(), ".") && path != "." {
				return filepath.SkipDir
			}
			return nil
		}
		if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
			return nil
		}
		src, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		for _, match := range literal.FindAllString(string(src), -1) {
			if !strings.Contains(match, "options.SkipPolymorphicDiscriminatorBackfill") {
				continue
			}
			checked++
			if !strings.Contains(match, "DeferFormulaViewRebuild") {
				t.Errorf("%s: packs.ApplyOptions mirror omits DeferFormulaViewRebuild without a deliberate-omission comment:\n%s", path, match)
			}
		}
		return nil
	})
	if walkErr != nil {
		t.Fatal(walkErr)
	}
	if checked == 0 {
		t.Fatal("guard found no ApplyOptions mirror sites; the detection pattern went stale")
	}
}
