package proxy

import (
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"

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

// NewProxy 创建反向代理
func NewProxy(targetURL string) (*httputil.ReverseProxy, error) {
	target, err := url.Parse(targetURL)
	if err != nil {
		return nil, err
	}
	proxy := httputil.NewSingleHostReverseProxy(target)
	originalDirector := proxy.Director
	proxy.Director = func(req *http.Request) {
		originalDirector(req)
		// 去除 /api/v1 前缀（Gateway 不改路径，直接透传给下游服务根路径）
		req.URL.Path = strings.TrimPrefix(req.URL.Path, "/api/v1")
		req.Host = target.Host
	}
	return proxy, nil
}

// ProxyHandler 返回 Gin 处理函数
func ProxyHandler(proxy *httputil.ReverseProxy) gin.HandlerFunc {
	return func(c *gin.Context) {
		proxy.ServeHTTP(c.Writer, c.Request)
	}
}
