package api

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

	"github.com/gin-gonic/gin"
	"github.com/pingcap/dbaas/central/config"
	"github.com/pingcap/errcode"
	"github.com/pingcap/errors"
)

func BillingProxy(c *gin.Context) {
	proxyPath := c.Params.ByName("any")

	target, err := url.Parse(config.Global().BillingConfig.Billing2BaseURL)
	if err != nil {
		err := errcode.NewInternalErr(errors.New("proxy error: billing address error"))
		Fail(c, err, http.StatusInternalServerError)
		return
	}

	director := func(req *http.Request) {
		req.URL.Scheme = target.Scheme
		req.URL.Host = target.Host
		req.URL.Path = proxyPath
	}
	proxy := &httputil.ReverseProxy{Director: director}
	proxy.ServeHTTP(c.Writer, c.Request)
}
