package server

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

	"github.com/gin-contrib/static"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"spahl.ddns.net/jasper/wok-able-backend/controllers"
)

var httpServer *http.Server
var httpRouter *gin.Engine

func proxy(c *gin.Context) {
	remote, err := url.Parse("http://localhost:3000")
	if err != nil {
		panic(err)
	}

	proxy := httputil.NewSingleHostReverseProxy(remote)

	proxy.Director = func(req *http.Request) {
		req.Header = c.Request.Header
		req.Host = remote.Host
		req.URL.Scheme = remote.Scheme
		req.URL.Host = remote.Host
		req.URL.Path = c.Request.URL.Path
	}
	proxy.ServeHTTP(c.Writer, c.Request)
}

func Setup(prodMode string) {
	httpRouter = gin.New()

	httpRouter.Use(gin.Logger())

	controllers.Setup(httpRouter)

	if prodMode == "release" {
		httpRouter.Use(static.Serve("/", static.LocalFile("./assets/dist", false)))
	} else {
		httpRouter.NoRoute(proxy)
		log.Info("using reverse proxy")
	}

	httpRouter.Run()
}
