package domain

import "testing"

func TestNormalizeSearchTerm(t *testing.T) {
	cases := []struct {
		in, want string
	}{
		{"  保母  求推薦  ", "保母 求推薦"},
		{"到府　保母", "到府 保母"},
		{"\t  ", ""},
	}
	for _, c := range cases {
		if got := NormalizeSearchTerm(c.in); got != c.want {
			t.Errorf("NormalizeSearchTerm(%q) = %q, want %q", c.in, got, c.want)
		}
	}
}

func TestIsThreadsSearchable(t *testing.T) {
	ok := []string{
		"保母 求推薦",
		"到府保母",
		"求推薦",
		"有人知道",
		"wedding photo",
		"台北 保母",
	}
	for _, s := range ok {
		if !IsThreadsSearchable(s) {
			t.Errorf("IsThreadsSearchable(%q) = false, want true", s)
		}
	}
	bad := []string{
		"",
		"a",
		"台北 婚攝 推薦", // 3 tokens
		"這是一個超長關鍵字超過十二字", // too long
		"保母 AND 求推薦",
		"保母#推薦",
		"保母！",
		"🎉 保母",
		"\"保母\"",
		"  ",
		"一", // 1 CJK rune
	}
	for _, s := range bad {
		if IsThreadsSearchable(s) {
			t.Errorf("IsThreadsSearchable(%q) = true, want false", s)
		}
	}
}

func TestSearchableTermVariantsKeepsShortAndShortensLong(t *testing.T) {
	got := SearchableTermVariants("保母 求推薦", true)
	if len(got) != 1 || got[0] != "保母 求推薦" {
		t.Fatalf("short term variants=%v", got)
	}
	got = SearchableTermVariants("晚上睡覺容易口乾舌燥怎麼辦", true)
	if len(got) == 0 {
		t.Fatal("long sentence produced no variants")
	}
	for _, term := range got {
		if !IsThreadsSearchable(term) {
			t.Fatalf("variant %q is not searchable", term)
		}
	}
	hasDry := false
	hasSleep := false
	for _, term := range got {
		if term == "口乾舌燥" {
			hasDry = true
		}
		if term == "晚上睡覺" {
			hasSleep = true
		}
	}
	if !hasDry || !hasSleep {
		t.Fatalf("variants=%v want 晚上睡覺 and 口乾舌燥", got)
	}
	got = SearchableTermVariants("台北 婚攝 推薦 價格", true)
	if len(got) == 0 || got[0] != "台北 婚攝" {
		t.Fatalf("multi-token variants=%v want 台北 婚攝 first", got)
	}
}

func TestExpandSearchTermsShortensUnsearchable(t *testing.T) {
	got := ExpandSearchTerms([]string{"求推薦", "晚上睡覺容易口乾舌燥怎麼辦"}, 20)
	if len(got) < 2 {
		t.Fatalf("expanded=%v", got)
	}
	if got[0] != "求推薦" {
		t.Fatalf("kept original first, got %v", got)
	}
	for _, term := range got {
		if !IsThreadsSearchable(term) {
			t.Fatalf("expanded term %q is not searchable", term)
		}
	}
}
