package engines

import (
	"context"
	"net/http"
	"testing"
	"time"

	"github.com/metamorphosis-dev/kafka/internal/contracts"
)

func TestGitHubEngine_EmptyQuery(t *testing.T) {
	eng := &GitHubEngine{}
	resp, err := eng.Search(context.Background(), contracts.SearchRequest{Query: ""})
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(resp.Results) != 0 {
		t.Errorf("expected 0 results for empty query, got %d", len(resp.Results))
	}
}

func TestGitHubEngine_Name(t *testing.T) {
	eng := &GitHubEngine{}
	if eng.Name() != "github" {
		t.Errorf("expected 'github', got %q", eng.Name())
	}
}

func TestGitHubEngine_Uninitialized(t *testing.T) {
	eng := &GitHubEngine{}
	_, err := eng.Search(context.Background(), contracts.SearchRequest{Query: "test"})
	if err == nil {
		t.Error("expected error for uninitialized client")
	}
}

func TestGitHubEngine_LiveRequest(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping live request")
	}

	client := &http.Client{}
	eng := &GitHubEngine{client: client}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	resp, err := eng.Search(ctx, contracts.SearchRequest{
		Query: "golang cli",
	})
	if err != nil {
		t.Fatalf("live search failed: %v", err)
	}

	if resp.NumberOfResults <= 0 {
		t.Error("expected some results for 'golang cli'")
	}
	if len(resp.Results) == 0 {
		t.Error("expected at least 1 result")
	}
	// Verify structure.
	for _, r := range resp.Results {
		if r.Engine != "github" {
			t.Errorf("expected engine 'github', got %q", r.Engine)
		}
		if r.URL == nil || *r.URL == "" {
			t.Error("expected non-empty URL")
		}
	}
	t.Logf("github returned %d results (total: %d)", len(resp.Results), resp.NumberOfResults)
}
