package placement

import (
	"context"
	"testing"

	libkg "haixun-backend/internal/library/knowledge"
	"haixun-backend/internal/library/websearch"
)

type stubWebSearch struct {
	enabled bool
	posts   []DiscoverPost
}

func (s stubWebSearch) Search(ctx context.Context, opts websearch.SearchOptions) (websearch.SearchResponse, error) {
	_ = ctx
	_ = opts
	results := make([]websearch.SearchResult, 0, len(s.posts))
	for _, post := range s.posts {
		results = append(results, websearch.SearchResult{
			Title:   post.Text,
			URL:     post.Permalink,
			Snippet: "",
		})
	}
	return websearch.SearchResponse{Status: "success", Results: results, Provider: websearch.ProviderBrave}, nil
}

func (s stubWebSearch) Enabled() bool                { return s.enabled }
func (s stubWebSearch) Provider() websearch.Provider { return websearch.ProviderBrave }

func TestDiscoverForQueryMergesWebSearchWhenBraveEnabled(t *testing.T) {
	input := DualTrackInput{
		Member: MemberContext{
			AllowsBrave:       true,
			AllowsThreadsAPI:  false,
			SearchSourceMode:  SearchSourceBrave,
			WebSearchProvider: string(websearch.ProviderBrave),
			BraveAPIKey:       "test-key",
		},
		WebSearch: stubWebSearch{
			enabled: true,
			posts: []DiscoverPost{{
				Text:      "最近洗衣精有推薦嗎？皮膚會癢",
				Permalink: "https://www.threads.net/@user1/post/abc123",
			}},
		},
		PatrolContext: PostScanContextFromPatrolInput(libkg.PatrolTagInput{
			ProductName: "天然洗衣精",
			MatchTags:   []string{"洗衣精"},
		}, nil),
	}
	tq := TagQuery{
		Tag:       "洗衣精 推薦",
		Query:     `site:threads.net 洗衣精 推薦`,
		Dimension: QueryRelevance,
	}
	posts, channel, err := discoverForQuery(context.Background(), input, tq, 5)
	if err != nil {
		t.Fatalf("discoverForQuery error: %v", err)
	}
	if len(posts) == 0 {
		t.Fatal("expected web search posts to be merged")
	}
	if channel != DiscoverBrave {
		t.Fatalf("expected brave channel, got %s", channel)
	}
}
