package middleware

import (
	"github.com/beego/beego/v2/server/web/context"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/infrastructure/api/authlib"
	"net/http"
	"strings"
	"time"
)

func JwtFilter() func(ctx *context.Context) {
	authLib := authlib.NewApiAuthLib(constant.AUTH_SERVER_HOST)
	authLib.BaseServiceGateway.ConnectTimeout = 200 * time.Millisecond
	authLib.BaseServiceGateway.ReadWriteTimeout = 200 * time.Millisecond
	return func(ctx *context.Context) {
		//token := ctx.Request.Header.Get("Authorization")
		token := ctx.Request.Header.Get("x-mmm-accesstoken")
		if len(token) > 0 {
			token = strings.TrimPrefix(token, "Bearer ")
			userToken := &domain.UserToken{}
			err := userToken.ParseToken(token)
			if err != nil {
				ctx.Output.SetStatus(http.StatusOK)
				ctx.Output.JSON(WithCodeMsgResponse(domain.InvalidRefreshToken), false, false)
				return
			}
			if userToken.UserId > 0 && userToken.CompanyId > 0 {
				loginCheckResponse, _ := authLib.LoginCheck(authlib.RequestLoginCheck{Token: token})
				if loginCheckResponse != nil && loginCheckResponse.Code == 901 {
					ctx.Output.SetStatus(http.StatusOK)
					ctx.Output.JSON(WithCodeMsgResponse(domain.InvalidRefreshToken), false, false)
					return
				}
			}
			ctx.Input.SetData("UserToken", userToken)
			ctx.Input.SetData("Accesstoken", token)
		}
	}
}

func WithCodeMsgResponse(code int) map[string]interface{} {
	msg := "token 过期或无效,需刷新令牌"
	if codeMsg, ok := domain.CodeMsg[code]; ok {
		msg = codeMsg
	}
	return map[string]interface{}{
		"msg":  msg,
		"code": code,
		"data": struct{}{},
	}
}