package main

import (
	"os"
	"strings"
	"testing"
)

func TestPkgSearch_FakeOutput(t *testing.T) {
	fake := "vim - Vi IMproved - enhanced vi editor\nvim-tiny - Vi IMproved - enhanced vi editor - compact version"
	os.Setenv("PKG_FAKE_OUTPUT", fake)
	defer os.Unsetenv("PKG_FAKE_OUTPUT")

	cap := &Capability{Name: "pkg.search"}
	res, code, err := runPkgSearch(cap, map[string]any{"query": "vim"})
	if err != nil {
		t.Fatalf("search: %v", err)
	}
	if code != 0 {
		t.Fatalf("code: %d", code)
	}
	m := res.(map[string]any)
	pkgs := m["packages"].([]map[string]any)
	if len(pkgs) != 2 {
		t.Fatalf("expected 2 pkgs, got %d", len(pkgs))
	}
	if pkgs[0]["name"] != "vim" {
		t.Fatalf("name mismatch: %v", pkgs[0]["name"])
	}
}

func TestPkgSearch_InvalidQuery(t *testing.T) {
	cap := &Capability{Name: "pkg.search"}
	_, _, err := runPkgSearch(cap, map[string]any{"query": "vim; rm -rf /"})
	if err == nil || !strings.Contains(err.Error(), "invalid char") {
		t.Fatalf("expected invalid char, got %v", err)
	}
}

func TestPkgSearch_NoQuery(t *testing.T) {
	cap := &Capability{Name: "pkg.search"}
	_, _, err := runPkgSearch(cap, map[string]any{})
	if err == nil || !strings.Contains(err.Error(), "query required") {
		t.Fatalf("expected query required, got %v", err)
	}
}
