package bundler

import (
	"strings"
	"testing"
)

// Compiling a Solid component should yield Solid's optimized dom output: a
// template clone, fine-grained insert, delegated events, and imports from
// solid-js/web — none of which a runtime factory would emit. TS types must be
// stripped too.
func TestCompileSolidComponent(t *testing.T) {
	src := `import { createSignal } from "solid-js";

interface Props { start: number }

export function Counter(props: Props) {
    const [c, setC] = createSignal<number>(props.start);
    return <button class="btn" onclick={() => setC(c() + 1)}>Count: {c()}</button>;
}
`
	out, err := Compile(src, "Counter.tsx")
	if err != nil {
		t.Fatalf("Compile: %v", err)
	}
	t.Logf("OUTPUT:\n%s", out)

	for _, want := range []string{
		`from "solid-js/web"`, // compiled helpers
		"_tmpl$",              // template clone
		"template(",           // template factory
		"createSignal",        // user code preserved
	} {
		if !strings.Contains(out, want) {
			t.Errorf("missing %q", want)
		}
	}
	// TS type syntax must be gone.
	for _, bad := range []string{"interface Props", ": Props", "<number>"} {
		if strings.Contains(out, bad) {
			t.Errorf("TS syntax leaked: %q", bad)
		}
	}
}

// A second call with identical input hits the cache and still returns the same
// compiled output.
func TestCompileCache(t *testing.T) {
	src := `export function A() { return <div>hi</div>; }`
	a, err := Compile(src, "A.tsx")
	if err != nil {
		t.Fatalf("first: %v", err)
	}
	b, err := Compile(src, "A.tsx")
	if err != nil {
		t.Fatalf("second: %v", err)
	}
	if a != b {
		t.Errorf("cached output differs")
	}
}
