package proxy

import (
	"net/http"

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

func dmHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		addr := req.Header.Get(constants.DMAddrHeader)
		if len(addr) == 0 {
			log.L().Warn("invalid dm addr", zap.String("path", req.URL.Path))
			http.Error(w, "dm addr is empty or missing", http.StatusBadRequest)
			return
		}

		proxy := GetReverseProxy(addr)
		proxy.Transport = &http.Transport{
			DisableKeepAlives: true,
		}
		proxy.ServeHTTP(w, req)
	})
}

func init() {
	registerProxyRoute(proxyRoute{
		name:    "dm",
		handler: dmHandler(),
	})
}
