package main

import "github.com/gin-gonic/gin"

// ServePathStartFromAny rewrites the request path by stripping the prefix
// before the "*any" route parameter, so downstream handlers (e.g. gRPC-gateway
// mux) see the canonical path (e.g. "/clusters/test:executeCommand") instead
// of the full prefixed path (e.g. "/cluster-agent/tidb123/api/v1/clusters/...").
//
// The original path is restored after ctx.Next() returns, so middleware that
// runs *after* this one in the post-handler phase (i.e. deferred logic in
// earlier middleware) will see the original, unprefixed path.
//
// For middleware ordering details, see the comment in newGatewayRouter where
// the middleware chain is defined.
func ServePathStartFromAny(ctx *gin.Context) {
	originalPath := ctx.Request.URL.Path
	originalRawPath := ctx.Request.URL.RawPath
	truePath := ctx.Param("any")
	if truePath == "" {
		ctx.Next()
		return
	}

	ctx.Request.URL.Path = truePath
	// Clear RawPath so downstream EscapedPath reflects the rewritten Path.
	ctx.Request.URL.RawPath = ""
	ctx.Next()
	ctx.Request.URL.Path = originalPath
	ctx.Request.URL.RawPath = originalRawPath
}
