package twitchclient

import (
	"context"
	"crypto/tls"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"

	"github.com/cactus/go-statsd-client/statsd"
)

func BenchmarkDo(b *testing.B) {
	ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer ts.Close()

	client, err := createClient(ts)
	if err != nil {
		b.Fatal(err)
	}

	req, err := client.NewRequest(http.MethodGet, "/foo", nil)
	if err != nil {
		b.Fatal(err)
	}

	reqOpts := ReqOpts{StatName: "bench"}
	ctx := context.WithValue(context.Background(), new(int), "var")

	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		_, err = client.Do(ctx, req, reqOpts)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func createClient(ts *httptest.Server) (Client, error) {
	parsedURL, err := url.Parse(ts.URL)
	if err != nil {
		return nil, err
	}

	statter, err := statsd.NewNoopClient()
	if err != nil {
		return nil, err
	}

	return NewClient(ClientConf{
		Host:            parsedURL.String(),
		Stats:           statter,
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	})
}
