package proxy

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

	"github.com/labstack/echo/v4"
)

type Handler struct {
	target *url.URL
	proxy  *httputil.ReverseProxy
}

func New(target string) (*Handler, error) {
	parsed, err := url.Parse(target)
	if err != nil {
		return nil, err
	}

	proxy := httputil.NewSingleHostReverseProxy(parsed)
	originalDirector := proxy.Director
	proxy.Director = func(req *http.Request) {
		originalDirector(req)
		req.Host = parsed.Host
		req.Header.Set("X-Forwarded-Host", req.Header.Get("Host"))
		req.Header.Set("X-Forwarded-Proto", scheme(req))
	}

	return &Handler{
		target: parsed,
		proxy:  proxy,
	}, nil
}

func (h *Handler) Handle(c echo.Context) error {
	h.proxy.ServeHTTP(c.Response(), c.Request())
	return nil
}

func scheme(req *http.Request) string {
	if req.TLS != nil {
		return "https"
	}
	if header := req.Header.Get("X-Forwarded-Proto"); header != "" {
		return header
	}
	return "http"
}
