package cluster

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"

	"k8s.io/client-go/kubernetes/fake"

	"github.com/tidbcloud/clusterproxy/resolve"
	"github.com/tidbcloud/clusterproxy/route"
)

func TestClusterProxy(t *testing.T) {
	for _, tc := range []struct {
		name              string
		path              string
		expectedErrorCode int
		getHandler        func(*route.Context, resolve.Cluster) http.Handler
		header            map[string]string
	}{
		{
			name:              "Prometheus",
			path:              "",
			getHandler:        promGetHandler,
			expectedErrorCode: http.StatusBadGateway,
		},
		{
			name:              "Kubernetes dashboard",
			path:              "",
			getHandler:        k8sDashboardGetHandler,
			header:            map[string]string{"Portal-Authorization": "Portal-Authorization"},
			expectedErrorCode: http.StatusBadGateway,
		},
		{
			name:              "PD dashboard",
			path:              "dashboard",
			getHandler:        pdGetHandler,
			expectedErrorCode: http.StatusInternalServerError,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			ctx := &route.Context{
				Cli: fake.NewSimpleClientset(),
			}
			req := &http.Request{
				URL:    &url.URL{Path: tc.path},
				Header: make(map[string][]string),
			}
			for k, v := range tc.header {
				req.Header.Set(k, v)
			}
			recorder := httptest.NewRecorder()

			cl := resolve.Cluster{Namespace: "tidb42"}
			tc.getHandler(ctx, cl).ServeHTTP(recorder, req)
			// The fake client set is not able to handle actual requests.
			if recorder.Code != tc.expectedErrorCode {
				t.Fatalf("Response code got = %v, want = %v.", recorder.Code, tc.expectedErrorCode)
			}
		})
	}

}
