package beego

import (
	"encoding/json"
	"github.com/beego/beego/v2/server/web/context"
	"os"
	"strconv"

	"github.com/beego/beego/v2/server/web"
	"github.com/linmadan/egglib-go/web/beego/filters"

	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
	_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/routers"
)

func init() {
	web.BConfig.AppName = "project"
	web.BConfig.CopyRequestBody = true
	web.BConfig.RunMode = "dev"
	web.BConfig.Listen.HTTPPort = 8080
	web.BConfig.Listen.EnableAdmin = false
	web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego/routers"
	if os.Getenv("RUN_MODE") != "" {
		web.BConfig.RunMode = os.Getenv("RUN_MODE")
	}
	if os.Getenv("HTTP_PORT") != "" {
		portStr := os.Getenv("HTTP_PORT")
		if port, err := strconv.Atoi(portStr); err == nil {
			web.BConfig.Listen.HTTPPort = port
		}
	}
	filters.SecureKeyMap["token"] = "x-mmm-accesstoken"
	web.InsertFilter("/*", web.BeforeRouter, filters.AllowCors())
	web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(log.Logger))
	web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(log.Logger), web.WithReturnOnOutput(false))
	web.InsertFilter("/v1/app/*", web.BeforeExec, filters.SecureHandler(
		filters.WithEnableCheckTimestamp(false),
		filters.WithOnInvalidRequest(func(ctx *context.Context) {
			headerData, _ := json.Marshal(ctx.Input.Context.Request.Header)
			log.Logger.Info("签名验证失败:" + string(headerData))
		}),
	))
}