package web

import (
	"regexp"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/valyala/fasthttp"
	proxy "github.com/yeqown/fasthttp-reverse-proxy"

	"tiup-log-collector/log"
	"tiup-log-collector/testutils"
	"tiup-log-collector/utils"
)

func setMixpanelProxyServer(t *testing.T, addr string) {
	t.Helper()
	mixpanelProxyServer = proxy.NewReverseProxy(addr)
}

func TestDashboardHandler(t *testing.T) {
	// disable proxy log
	proxy.SetProduction()

	setMixpanelProxyServer(t, "0.0.0.0")

	cfg := log.Config{}
	cfg.SentryDSN = "test"

	t.Run("should proxy request", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/track?data=e30%3D")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertLogNextLineMatch(t, regexp.MustCompile(`.*"app":"dashboard".*`))
		assert.Equal(t, "/track", utils.String(ctx.Path()), "path not change")

		testutils.ResetTestLogger()
	})

	t.Run("should log each items", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		// "data=[1,2,3]"
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/track?data=WzEsMiwzXQ%3D%3D")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertLogNextLineMatch(t, regexp.MustCompile(`.*"content":1.*`))
		testutils.AssertLogNextLineMatch(t, regexp.MustCompile(`.*"content":2.*`))
		testutils.AssertLogNextLineMatch(t, regexp.MustCompile(`.*"content":3.*`))
		testutils.AssertNoLog(t)
		assert.Equal(t, "/track", utils.String(ctx.Path()), "path not change")

		testutils.ResetTestLogger()
	})

	t.Run("should only log 'track' requests", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/foo?data=e30%3D")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertNoLog(t)

		testutils.ResetTestLogger()
	})

	t.Run("should not process request without param 'data'", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/track")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertNoLog(t)

		testutils.ResetTestLogger()
	})

	t.Run("should not log request with bad data base64 encode", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/track?data={")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertNoLog(t)

		testutils.ResetTestLogger()
	})

	t.Run("should not log request with bad data json format", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}
		// "data={"
		ctx.Request.SetRequestURI("http://foo.bar/api/v1/dashboard/report/track?data=ew==")

		testutils.InitTestLogger()
		dashboardHandler(&ctx)

		testutils.AssertNoLog(t)

		testutils.ResetTestLogger()
	})
}
