package proxy

import (
	"crypto/tls"
	"net/http"

	"github.com/pingcap/log"
	"github.com/tidbcloud/dataflow-service/internal/constants"
	"go.uber.org/zap"
)

func lightningHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		addr := req.Header.Get(constants.LightningAddrHeader)
		if len(addr) == 0 {
			log.Warn("invalid lightning addr", zap.String("path", req.URL.Path))
			http.Error(w, "lightning addr is empty or missing", http.StatusBadRequest)
			return
		}
		proxy := GetReverseProxy(addr)
		proxy.Transport = &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true, // nolint:gosec
			},
			DisableKeepAlives: true,
		}
		proxy.ServeHTTP(w, req)
	})
}

func init() {
	registerProxyRoute(proxyRoute{
		name:    "lightning",
		handler: lightningHandler(),
	})
}
