package fullstack_test

import (
	"os"
	"path/filepath"
	"testing"

	"git.cloudinit.dev/coreci/orca/internal/jobspec"
	"git.cloudinit.dev/coreci/orca/internal/spec/schema"
)

// TestExamplesValidate parses and validates every jobspec in
// examples/full-stack/ against the current parser and schema validators
// (gate C-20, REQ-094). This ensures the example jobspecs use only
// fields that exist in the current WorkloadSpec struct and pass the
// per-kind validators.
func TestExamplesValidate(t *testing.T) {
	dir := filepath.Join("..", "..", "examples", "full-stack")
	entries, err := os.ReadDir(dir)
	if err != nil {
		t.Fatalf("read examples dir: %v", err)
	}
	for _, e := range entries {
		if e.IsDir() {
			continue
		}
		name := e.Name()
		// Skip README.md and other non-jobspec markdown files.
		if name == "README.md" {
			continue
		}
		ext := filepath.Ext(name)
		if ext != ".md" && ext != ".yaml" && ext != ".yml" {
			continue
		}
		t.Run(name, func(t *testing.T) {
			path := filepath.Join(dir, name)
			spec, err := jobspec.ParseFile(path)
			if err != nil {
				t.Fatalf("ParseFile %s: %v", name, err)
			}
			if spec == nil {
				t.Fatalf("ParseFile %s: spec is nil", name)
			}
			if spec.Kind == "" {
				t.Fatalf("ParseFile %s: kind is empty", name)
			}
			if spec.Name == "" {
				t.Fatalf("ParseFile %s: name is empty", name)
			}
			validator, err := schema.ValidatorFor(spec.Kind)
			if err != nil {
				t.Fatalf("ValidatorFor %s (kind %s): %v", name, spec.Kind, err)
			}
			if err := validator.Validate(spec); err != nil {
				t.Fatalf("Validate %s: %v", name, err)
			}
		})
	}
}
