// Package middleware ...
//
// Description : middleware ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-06-25 23:07
package middleware

import (
	"fmt"
	"strings"
	"time"

	"git.zhangdeman.cn/zhangdeman/wrapper/op_string"

	"git.zhangdeman.cn/zhangdeman/gin/define"

	networkUtil "git.zhangdeman.cn/zhangdeman/network/util"
	"github.com/gin-gonic/gin"
)

// InitRequest 初始化请求
func InitRequest(ctx *gin.Context) {
	httpHandleConfig := define.GetHttpHandleConfig()
	requestID := getRequestID(ctx)
	traceID := getTraceID(ctx, requestID)
	ctx.Set(httpHandleConfig.TraceIDField, traceID)
	ctx.Set(httpHandleConfig.RequestIDField, requestID)
	ctx.Set(httpHandleConfig.StartRequestTimeField, time.Now().UnixMilli())
	ctx.Next()
}

// getRequestID 生成 request id
func getRequestID(ctx *gin.Context) string {
	return fmt.Sprintf(
		"%v-%v-%v-%v",
		time.Now().UnixNano()/1e6,
		strings.ReplaceAll(networkUtil.IP.GetHostIP(), ".", ""),
		strings.ReplaceAll(networkUtil.IP.GetRemoteIP(ctx.Request), ".", ""),
		op_string.Md5(op_string.Random(32, "")).Value,
	)
}

// getTraceID 生成 trace id
func getTraceID(ctx *gin.Context, requestID string) string {
	traceID := ctx.GetHeader("X-Forward-Trace-Id")
	if len(traceID) > 0 {
		return traceID
	}
	if len(requestID) > 0 {
		return requestID
	}
	return getRequestID(ctx)
}
