// Package proxy add by blacknc <blacknc@163.com> at 2024/11/22 10:25:37
package proxy

import (
	"net/http"
	"strconv"
	"tcidm/internal/service/utils"

	"github.com/tidbcloud/tiinf/monitor/tilog"
	"go.uber.org/zap"
)

func init() {
	registerProxyRoute(proxyRoute{
		name:    "dataflow-agent",
		handler: dataflowAgentHandler(),
	})
}

const ClusterIDHeader = "X-TIDB-ClusterID"

func dataflowAgentHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		clusterIDStr := req.Header.Get(ClusterIDHeader)
		if clusterIDStr == "" {
			tilog.Error(ctx, "header X-TIDB-ClusterID is required", zap.String("path", req.URL.Path))
			http.Error(w, "header X-TIDB-ClusterID is empty or missing", http.StatusBadRequest)
			return
		}
		clusterID, err := strconv.ParseUint(clusterIDStr, 10, 64)
		if err != nil || clusterID == 0 {
			tilog.Error(ctx, "header X-TIDB-ClusterID is invalid", zap.String("clusterIDStr", clusterIDStr), zap.String("path", req.URL.Path))
			http.Error(w, "header X-TIDB-ClusterID is invalid", http.StatusBadRequest)
			return
		}

		dataflowAgentUrl, err := utils.GetDataflowAgentUrl(ctx, clusterID)
		if err != nil || dataflowAgentUrl == "" {
			tilog.Error(ctx, "GetDataflowAgentUrl failed", zap.Uint64("clusterID", clusterID), zap.String("path", req.URL.Path), zap.Error(err))
			http.Error(w, "failed to get dataflow-agent url", http.StatusInternalServerError)
			return
		}
		// The agent address does not come with a schema by default, so it needs to be added
		dataflowAgentUrl = "http://" + dataflowAgentUrl
		tilog.Info(ctx, "proxy to dataflow-agent", zap.String("agent-addr", dataflowAgentUrl))

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