package server

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

	"sigs.k8s.io/controller-runtime/pkg/client"

	"github.com/tidbcloud/observability/agent-control-server/pkg/config"
	"github.com/tidbcloud/observability/agent-control-server/pkg/testkits"
)

func makeTestServer(objects ...client.Object) *Server {
	fakeCli := testkits.BuildClient(objects...)
	return New(":8080", fakeCli, &config.RootConfig{})
}

func makeGetRequest(path string) *http.Request {
	return httptest.NewRequest(http.MethodGet, path, nil)
}

func makePostRequest(path string, body any) *http.Request {
	var reqBody bytes.Buffer
	if body != nil {
		_ = json.NewEncoder(&reqBody).Encode(body)
	}
	return httptest.NewRequest(http.MethodPost, path, &reqBody)
}

func parseResponse(w *httptest.ResponseRecorder) CommonResponse {
	var rsp CommonResponse
	_ = json.Unmarshal(w.Body.Bytes(), &rsp)
	return rsp
}

func parseResponseData[T any](rsp CommonResponse) T {
	bs, _ := json.Marshal(rsp.Data)
	var ret T
	_ = json.Unmarshal(bs, &ret)
	return ret
}
