package tests

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"

	"github.com/pingcap/dbaas/billing2/middleware"

	"github.com/pingcap/dbaas/billing2/utils/panicIf"
)

func PerformRequestWithHeaders(router http.Handler, method string, path string, input interface{}, headers map[string]string) *httptest.ResponseRecorder {
	var inputBytes []byte
	var err error
	if input != nil {
		inputBytes, err = json.Marshal(input)
		panicIf.Error(err)
	}
	req, _ := http.NewRequest(method, path, bytes.NewReader(inputBytes))
	for key, val := range headers {
		req.Header.Set(key, val)
	}
	w := httptest.NewRecorder()
	router.ServeHTTP(w, req)
	return w
}

func PerformGetRequest(router http.Handler, path string) *httptest.ResponseRecorder {
	return PerformRequestWithHeaders(router, "GET", path, nil, nil)
}

func PerformRequest(router http.Handler, method string, path string, input interface{}) *httptest.ResponseRecorder {
	return PerformRequestWithHeaders(router, method, path, input, nil)
}

func PerformRequestWithOpenAPIHeader(router http.Handler, method string, path string, input interface{}) *httptest.ResponseRecorder {
	s, _ := json.Marshal(middleware.OpenAPIAuthResult{PublicKey: "s"})
	headers := map[string]string{
		"X-Auth-Type":    "openapi",
		"X-Auth-Content": string(s),
	}
	return PerformRequestWithHeaders(router, method, path, input, headers)
}
