package suggest

import (
	"reflect"
	"testing"
)

func TestParseDuckDuckGoTypeList(t *testing.T) {
	body := []byte(`["iphone case",["iphone case holder","iphone case cute","iphone case leather"]]`)
	got := parseDuckDuckGo(body, 2)
	want := []string{"iphone case holder", "iphone case cute"}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("type=list parse = %v, want %v", got, want)
	}
}

func TestParseDuckDuckGoPhraseObjects(t *testing.T) {
	body := []byte(`[{"phrase":"iphone case holder"},{"phrase":"iphone case cute"}]`)
	got := parseDuckDuckGo(body, 10)
	want := []string{"iphone case holder", "iphone case cute"}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("phrase parse = %v, want %v", got, want)
	}
}

func TestParseDuckDuckGoUnexpectedShape(t *testing.T) {
	cases := map[string][]byte{
		"error object":    []byte(`{"error":"boom"}`),
		"empty list":      []byte(`[]`),
		"not json":        []byte(`not json`),
		"no phrase field": []byte(`[{"other":"x"}]`),
		"single non-list": []byte(`["only-seed"]`),
		"list second odd": []byte(`["seed","not-an-array"]`),
		"number list":     []byte(`[1,2,3]`),
	}
	for name, body := range cases {
		if got := parseDuckDuckGo(body, 10); got != nil {
			t.Errorf("%s: parse = %v, want nil (trigger google fallback)", name, got)
		}
	}
}

func TestParseDuckDuckGoStripsMarkup(t *testing.T) {
	body := []byte(`["q",["<b>bold</b> idea","  padded  ",""]]`)
	got := parseDuckDuckGo(body, 10)
	want := []string{"bold idea", "padded"}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("clean parse = %v, want %v", got, want)
	}
}

func TestParseGoogleSuggestions(t *testing.T) {
	body := []byte(")]}'\n[[[\"iphone case holder\",0],[\"iphone case cute\",0]]]")
	got := parseGoogleSuggestions(body, 10)
	want := []string{"iphone case holder", "iphone case cute"}
	if !reflect.DeepEqual(got, want) {
		t.Fatalf("xssi parse = %v, want %v", got, want)
	}

	plain := []byte(`[[["crochet hat",0],["crochet hat pattern",0]]]`)
	got = parseGoogleSuggestions(plain, 1)
	if !reflect.DeepEqual(got, []string{"crochet hat"}) {
		t.Fatalf("plain parse with cap = %v", got)
	}

	if got := parseGoogleSuggestions([]byte(`{"weird":1}`), 10); got != nil {
		t.Fatalf("garbage parse = %v, want nil", got)
	}
}
