package sfcrmappservice

import (
	"net/http"
	"strings"

	querycodec "github.com/pingcap-inc/nexuscrm-app-packs/sfcrm/querycodec"
)

// redirectLegacyQuerySlash reproduces Gin's GET collection redirect before
// authentication. The canonical request still uses the unchanged codec and
// Runtime authorization path; only one terminal slash is accepted.
func redirectLegacyQuerySlash(w http.ResponseWriter, r *http.Request) bool {
	if r.Method != http.MethodGet || !strings.HasSuffix(r.URL.Path, "/") {
		return false
	}
	canonical := strings.TrimSuffix(r.URL.Path, "/")
	route, ok := querycodec.Match(canonical)
	if !ok || (route.Kind != querycodec.RouteQuery && route.Kind != querycodec.RouteQueryAll) {
		return false
	}
	if r.URL.RawQuery != "" || r.URL.ForceQuery {
		canonical += "?" + r.URL.RawQuery
	}
	http.Redirect(w, r, canonical, http.StatusMovedPermanently)
	return true
}
