package shodan

import (
	"net/http"
	"testing"

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

func TestClient_CountExploits_nilOptions(t *testing.T) {
	_, err := client.CountExploits(nil)
	assert.NotNil(t, err)
	assert.EqualValues(t, ErrInvalidQuery, err)
}

func TestClient_CountExploits_emptyQuery(t *testing.T) {
	_, err := client.CountExploits(&ExploitSearchOptions{})
	assert.NotNil(t, err)
	assert.EqualValues(t, ErrInvalidQuery, err)
}

func TestClient_CountExploits_noFacets(t *testing.T) {
	setUpTestServe()
	defer tearDownTestServe()

	mux.HandleFunc(exploitCountPath, func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "GET", r.Method)
		w.Write(getStub(t, "exploits/exploits_count_no_facets"))
	})

	expectedExploitsCount := &ExploitSearch{Total: 40, Matches: []*Exploit{}}
	options := &ExploitSearchOptions{Query: "port=22"}
	exploitsCount, err := client.CountExploits(options)

	assert.Nil(t, err)
	assert.Equal(t, expectedExploitsCount, exploitsCount)
}

func TestClient_CountExploits_facets(t *testing.T) {
	setUpTestServe()
	defer tearDownTestServe()

	mux.HandleFunc(exploitCountPath, func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "GET", r.Method)
		w.Write(getStub(t, "exploits/exploits_count_facets"))
	})

	expectedExploitsCount := &ExploitSearch{
		Total:   40,
		Matches: []*Exploit{},
		Facets: map[string][]*Facet{
			"platform": {
				&Facet{
					Count: 24,
					Value: "Windows",
				},
				&Facet{
					Count: 5,
					Value: "OSX",
				},
			},
			"author": {
				&Facet{
					Count: 9,
					Value: "juan vazquez <juan.vazquez@metasploit.com>",
				},
				&Facet{
					Count: 7,
					Value: "sinn3r <sinn3r@metasploit.com>",
				},
			},
		},
	}
	options := &ExploitSearchOptions{
		Query:  "type=exploit",
		Facets: "platform,author",
	}
	exploitsCount, err := client.CountExploits(options)

	assert.Nil(t, err)
	assert.Equal(t, expectedExploitsCount, exploitsCount)
}

func TestClient_SearchExploits_nilOptions(t *testing.T) {
	_, err := client.SearchExploits(nil)
	assert.NotNil(t, err)
	assert.EqualValues(t, ErrInvalidQuery, err)
}

func TestClient_SearchExploits_emptyQuery(t *testing.T) {
	_, err := client.SearchExploits(&ExploitSearchOptions{})
	assert.NotNil(t, err)
	assert.EqualValues(t, ErrInvalidQuery, err)
}
