package search

import (
	"context"
	"encoding/json"
	"os"
	"path/filepath"
	"testing"

	"github.com/yourorg/devour/internal/config"
)

func TestEngineRebuildAndSearch(t *testing.T) {
	tmp := t.TempDir()
	docsDir := filepath.Join(tmp, "docs")
	indexDir := filepath.Join(tmp, "index")
	metaDir := filepath.Join(tmp, "metadata")
	if err := os.MkdirAll(docsDir, 0o755); err != nil {
		t.Fatal(err)
	}

	doc := map[string]any{
		"id":      "1",
		"title":   "HTTP Client",
		"content": "Use net/http client with timeout",
		"type":    "go-doc",
		"source":  "go",
		"url":     "https://pkg.go.dev/net/http",
	}
	b, _ := json.Marshal(doc)
	if err := os.WriteFile(filepath.Join(docsDir, "doc.json"), b, 0o644); err != nil {
		t.Fatal(err)
	}

	cfg := config.Default()
	cfg.Storage.DocsDir = docsDir
	cfg.Storage.IndexDir = indexDir
	cfg.Storage.MetadataDir = metaDir

	e := NewEngine(cfg)
	stats, err := e.Rebuild(context.Background())
	if err != nil {
		t.Fatalf("rebuild failed: %v", err)
	}
	if stats.Documents == 0 {
		t.Fatal("expected documents in index")
	}

	results, _, err := e.Search(context.Background(), "http timeout", SearchOptions{Limit: 5})
	if err != nil {
		t.Fatalf("search failed: %v", err)
	}
	if len(results) == 0 {
		t.Fatal("expected at least one search result")
	}
}
