package test_utils

import (
	"context"
	"fmt"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/dlsniper/debugger"
	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/handler_utils"
	"gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/logs"
	"golang.ngrok.com/ngrok"
	"golang.ngrok.com/ngrok/config"
	"net/http"
	"os"
	"os/exec"
)

func StartTestHandler(context context.Context, apiHandler lambda.Handler, sqsHandler lambda.Handler) {
	if os.Getenv("DEBUG_PROXY") == "true" {
		StartProxy()
	}

	http.HandleFunc("/sqs/", debugger.Middleware(func(writer http.ResponseWriter, request *http.Request) {
		handler_utils.ServeSQSFunctions(context, sqsHandler, writer, request)
	}, func(r *http.Request) []string {
		return []string{
			"path", r.RequestURI,
		}
	}))

	http.HandleFunc("/", debugger.Middleware(func(writer http.ResponseWriter, request *http.Request) {
		handler_utils.ServeHTTPFunctions(context, apiHandler, writer, request)
	}, func(r *http.Request) []string {
		return []string{
			"path", r.RequestURI,
		}
	}))

	// Create ngrok tunnel
	if os.Getenv("NGROK_ENABLED") == "true" {
		go func() {
			// Serve ngrok tunnel
			tun, _ := ngrok.Listen(context, config.HTTPEndpoint(), ngrok.WithAuthtoken(os.Getenv("NGROK_AUTHTOKEN")))
			os.Setenv("OVERWRITTEN_CORE_API_URL", tun.URL())
			fmt.Println(fmt.Sprintf("Ngrok tunnel created: %s", tun.URL()))
			_ = http.Serve(tun, nil)
		}()
	}

	_ = http.ListenAndServe(":3000", nil)
}

func StartProxy() {
	// Import "Map Remote" config file to Proxyman:
	// [{"id":"A389B009-E949-4944-8D66-95799C6923DC","name":"Bob Pay","preserveOriginalURL":true,"regex":"useWildcard","graphQLQueryName":null,"isEnabled":true,"fromURLComponent":{"path":"","query":"","host":"","scheme":"","port":""},"preserveHostHeader":true,"mapFromURL":"https:\/\/api.dev.bobpay.co.za\/*","isIncludingPaths":true,"toURLComponent":{"path":"","query":"","host":"localhost","scheme":"http","port":"3000"},"method":{"any":{}}}]

	// Check if Proxyman is installed https://proxyman.io/
	filePath, err := exec.Command("mdfind", "-name", "kMDItemFSName=='Proxyman.app'").Output()
	if err != nil {
		panic(err)
	}

	if len(filePath) == 0 {
		logs.Info("Not starting Proxy")
		return
	}

	cmd := exec.Command("open", "-gj", "-a", "/Applications/Proxyman.app")
	err = cmd.Start()
	if err != nil {
		panic(err)
	}

	cmd = exec.Command("/Applications/Proxyman.app/Contents/MacOS/proxyman-cli", "proxy", "on")
	err = cmd.Start()
	if err != nil {
		panic(err)
	}
}