// package cluster provides services and proxies related to the Kubernetes cluster.
package cluster

import (
	"net/http"

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

const (
	k8sDashboardNamespace     = "kubernetes-dashboard"
	k8sDashboardServiceName   = "kubernetes-dashboard"
	k8sDashboardPort          = "80"
	portalAuthorizationHeader = "Portal-Authorization"
)

func init() {
	router.RegisterRoute(k8sDashboardRoute)
}

var k8sDashboardRoute = &route.Route{
	Name:    "k8s",
	Path:    "kubernetes_dashboard",
	Version: route.V1,
	Schema: &route.Schema{
		PathRegex:       `.*`,
		RequiredHeaders: []string{},
		JSONBodyModel:   nil,
	},
	GetHandler: k8sDashboardGetHandler,
}

func k8sDashboardGetHandler(c *route.Context, _ resolve.Cluster) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		portalAuthHeader := r.Header.Get(portalAuthorizationHeader)
		if portalAuthHeader == "" {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		r.Header.Set("Authorization", portalAuthHeader)

		route.GetKubernetesServiceProxy("http", k8sDashboardNamespace, k8sDashboardServiceName, k8sDashboardPort, nil).ServeHTTP(w, r)
	})
}
