package controller

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

	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
)

type WafLogController struct {
	remote       string
	regionUrlMap map[string]string
}

func NewWafLogController(regionUrlMap map[string]string) *WafLogController {
	return &WafLogController{
		regionUrlMap: regionUrlMap,
	}
}

func (c *WafLogController) WafLogProxy(ctx *gin.Context) {
	region := ctx.Query("region_code")
	remoteUrl, err := url.Parse(c.regionUrlMap[region])
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	log.Info().Msgf("remoteUrl: %s", remoteUrl.String())

	// proxy := httputil.NewSingleHostReverseProxy(remoteUrl)
	// proxy.Rewrite = func(req *httputil.ProxyRequest) {
	// 	req.Out.URL.Path = strings.Replace(req.In.URL.Path, "/api/v2/containerSec/waf", "/api/v2/waf", 1)
	// 	req.Out.Host = remoteUrl.Host
	// }
	proxy := &httputil.ReverseProxy{
		Rewrite: func(req *httputil.ProxyRequest) {
			req.Out.URL.Scheme = remoteUrl.Scheme
			req.Out.URL.RawQuery = req.In.URL.RawQuery
			req.Out.URL.Host = remoteUrl.Host
			req.Out.URL.Path = strings.Replace(req.In.URL.Path, "/api/v2/containerSec/waf", "/api/v2/waf", 1)
		},
	}

	proxy.ServeHTTP(ctx.Writer, ctx.Request)

}
