package cluster

import (
	"fmt"
	"net/http"
	"time"

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

const (
	tiflashServiceFormat = "%s-tiflash-peer"
	tiflashPort          = "20292"
)

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

var tiflashRoute = &route.Route{
	Name:    "tiflash",
	Path:    "tiflash",
	Version: route.V1,
	Schema: &route.Schema{
		PathRegex:       `.*`,
		RequiredHeaders: []string{},
		JSONBodyModel:   nil,
	},
	GetHandler: tiflashGetHandler,
}

func tiflashGetHandler(c *route.Context, cl resolve.Cluster) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		scheme := httpsScheme
		namespace := cl.Namespace
		tiflashServiceName := fmt.Sprintf(tiflashServiceFormat, cl.Name)
		tlsClientSecretName := fmt.Sprintf(tlsClientSecretFormat, cl.Name)
		config, err := util.GetTLSConfig(c.Cli, namespace, cl.Name, tlsClientSecretName)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		if config == nil {
			scheme = httpScheme
		}

		proxy := route.GetKubernetesServiceProxy(scheme, namespace, tiflashServiceName, tiflashPort, &http.Transport{
			TLSClientConfig: config,
			MaxIdleConns:    1,
			IdleConnTimeout: 30 * time.Second,
		})
		proxy.ServeHTTP(w, r)
	})
}
