package server

import (
	"net/http"
	"strings"

	"github.com/pingcap/agent-git-service/internal/rest"
	"github.com/pingcap/agent-git-service/internal/rest/transform"
)

// ServeWithPublicURLBase runs one embedded AGS request with a trusted,
// request-owned public URL base. The context marker makes handlers fail closed
// if the base is lost, while transform.Wrap covers every legacy response
// transformer without mutating the process-wide Standalone base.
func ServeWithPublicURLBase(next http.Handler, writer http.ResponseWriter, request *http.Request, baseURL string) {
	baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
	if next == nil || request == nil || baseURL == "" {
		http.Error(writer, "request public URL authority is unavailable", http.StatusInternalServerError)
		return
	}
	request = rest.RequirePublicURLBase(rest.WithPublicURLBase(request, baseURL))
	transform.Wrap(baseURL, func() {
		next.ServeHTTP(writer, request)
	})
}
