package web

import (
	"regexp"
	"testing"

	"github.com/valyala/fasthttp"

	"tiup-log-collector/testutils"
)

func TestOtherHandler(t *testing.T) {
	t.Run("should response 404", func(t *testing.T) {
		req := testutils.NewMockRequest("", "")

		res := testutils.AssertMockServe(t, req, otherHandler)

		testutils.AssertResponse(t, res, 404, `{"detail":"404 not found"}`)
	})
}

func TestPingHandler(t *testing.T) {
	t.Run("should response pong", func(t *testing.T) {
		req := testutils.NewMockRequest("", "")

		res := testutils.AssertMockServe(t, req, pingHandler)

		testutils.AssertResponse(t, res, 200, `{"detail":"pong"}`)
	})
}

func TestEventHandler(t *testing.T) {
	t.Run("should failed if body is not json", func(t *testing.T) {
		req := testutils.NewMockRequest("", "{")

		res := testutils.AssertMockServe(t, req, func(ctx *fasthttp.RequestCtx) {
			eventHandler(ctx, "test-app")
		})

		testutils.AssertResponse(t, res, 400, `{"detail":"Invalid content, required json."}`)
	})

	t.Run("should succeed if body is json", func(t *testing.T) {
		req := testutils.NewMockRequest("", `{"foo":"bar"}`)

		res := testutils.AssertMockServe(t, req, func(ctx *fasthttp.RequestCtx) {
			eventHandler(ctx, "test-app")
		})

		testutils.AssertResponse(t, res, 200, `{"detail":"success"}`)
	})

	t.Run("should output correct log", func(t *testing.T) {
		testutils.InitTestLogger()

		ctx := fasthttp.RequestCtx{}
		ctx.Request.AppendBodyString(`{"foo":"bar"}`)

		eventHandler(&ctx, "test-app")
		testutils.AssertLogNextLineMatch(t, regexp.MustCompile(`^{"ts":\d+\.\d+,"host":"[^"]+","ip":"\d+\.\d+\.\d+\.\d+","app":"test-app","content":{"foo":"bar"}}$`))

		testutils.ResetTestLogger()
	})
}
