package reqmodifier

import (
	"strings"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/tidb-management-service/tidb-mgmt-portal/pkg/consts"
)

func ServePathStartFromAny(ctx *gin.Context) {
	originalPath := ctx.Request.URL.Path
	ctx.Request.Header.Add(consts.DomainKey, strings.Split(originalPath, "/")[1])
	ctx.Request.URL.Path = ctx.Param("any")
	ctx.Next()
	ctx.Request.URL.Path = originalPath
}

// RewriteBracketParams automatically converts arr[]=1&arr[]=2 -> arr=1&arr=2 for all keys.
func RewriteBracketParams() gin.HandlerFunc {
	return func(c *gin.Context) {
		query := c.Request.URL.Query() // type: url.Values
		changed := false

		for key, values := range query {
			if before, ok := strings.CutSuffix(key, "[]"); ok {
				newKey := before

				// Append to the new key
				query[newKey] = append(query[newKey], values...)
				// Remove the old bracketed key
				delete(query, key)
				changed = true
			}
		}

		if changed {
			// Update the request's RawQuery
			c.Request.URL.RawQuery = query.Encode()
		}

		c.Next()
	}
}
