package websearch

import (
	"context"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestSearchBrave(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if got := r.Header.Get("X-Subscription-Token"); got != "test-key" {
			t.Fatalf("unexpected token header: %q", got)
		}
		if got := r.URL.Query().Get("q"); got != "Jane Doe Acme" {
			t.Fatalf("unexpected query: %q", got)
		}
		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write([]byte(`{
			"web": {
				"results": [
					{"title": "Jane Doe - LinkedIn", "url": "https://linkedin.com/in/jane", "description": "CEO at Acme"}
				]
			}
		}`))
	}))
	defer srv.Close()

	oldURL := braveSearchURL
	braveSearchURL = srv.URL
	t.Cleanup(func() { braveSearchURL = oldURL })

	client := NewClient()
	results, err := client.Search(context.Background(), Provider{
		Type:   ProviderBrave,
		APIKey: "test-key",
	}, "Jane Doe Acme", 5)
	if err != nil {
		t.Fatalf("Search: %v", err)
	}
	if len(results) != 1 || results[0].Title != "Jane Doe - LinkedIn" {
		t.Fatalf("unexpected results: %#v", results)
	}
}

func TestBuildContactSearchQuery(t *testing.T) {
	got := BuildContactSearchQuery("Jean", "Dupont", "Marie", "Ultimail", "CTO", "Lyon")
	want := "Jean Marie Dupont Ultimail CTO Lyon"
	if got != want {
		t.Fatalf("BuildContactSearchQuery() = %q, want %q", got, want)
	}
	if BuildContactSearchQuery("", "", "", "", "", "") != "" {
		t.Fatal("expected empty query")
	}
}

func TestFormatResultsForPrompt(t *testing.T) {
	text := FormatResultsForPrompt([]Result{
		{Title: "Profil", URL: "https://example.com", Description: "Bio"},
	})
	if text == "" {
		t.Fatal("expected non-empty prompt section")
	}
	for _, part := range []string{"homonymes", "Profil", "https://example.com", "Bio"} {
		if !strings.Contains(text, part) {
			t.Fatalf("missing %q in: %s", part, text)
		}
	}
}

func TestResolveProvider(t *testing.T) {
	settings := Settings{
		DefaultProviderID: "brave-1",
		Providers: []Provider{{
			ID: "brave-1", Name: "Brave", Type: ProviderBrave, APIKey: "key",
		}},
	}
	p, err := ResolveProvider(settings)
	if err != nil {
		t.Fatalf("ResolveProvider: %v", err)
	}
	if p.ID != "brave-1" {
		t.Fatalf("unexpected provider: %#v", p)
	}
}
