package usecase

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/stretchr/testify/require"
)

func TestExaThreadsProviderSearchesThreadsDomains(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		require.Equal(t, http.MethodPost, r.Method)
		require.Equal(t, "test-key", r.Header.Get("x-api-key"))
		var body map[string]any
		require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
		require.Equal(t, []any{"threads.net", "threads.com"}, body["includeDomains"])
		require.NotContains(t, body, "startPublishedDate")
		_, _ = w.Write([]byte(`{"results":[{"title":"Not a Threads post","url":"https://example.com/post/1","highlights":["Ignore me"]},{"title":"Example","url":"https://www.threads.net/@alice/post/1","highlights":["A matching post"]}]}`))
	}))
	defer server.Close()

	provider := NewExaThreadsProvider("test-key")
	provider.BaseURL = server.URL
	results, err := provider.SearchThreads(context.Background(), []string{"sensitive skin"}, 1)
	require.NoError(t, err)
	require.Equal(t, []ThreadSearchResult{{
		URL: "https://www.threads.net/@alice/post/1", Title: "Example", Snippet: "A matching post",
	}}, results)
}

func TestExaThreadsProviderRejectsMissingKey(t *testing.T) {
	_, err := NewExaThreadsProvider("").SearchThreads(context.Background(), []string{"query"}, 1)
	require.Error(t, err)
}
