package h_validate_request_header

import (
	"cicv-data-closedloop/common/config/c_log"
	"cicv-data-closedloop/common/entity"
	"encoding/json"
	"fmt"
	"net/http"
)

var token = "1e8YmQMYwTTbfUYMZczkj1x17AeXjbdU"

// HeaderValidationMiddleware Middleware function to add header validation
func HeaderValidationMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		acceptToken := r.Header["Authorization"]
		if _, ok := r.Header["Authorization"]; !ok {
			c_log.GlobalLogger.Errorf("未添加请求头 Authorization：%v", acceptToken)
			result, _ := json.Marshal(entity.HttpResult{Status: false, Code: "1000", Message: "未添加请求头 Authorization。"})
			_, _ = fmt.Fprintf(w, string(result))
			return
		}
		if acceptToken[0] != token {
			c_log.GlobalLogger.Errorf("请求头 Authorization 校验失败：%v --> %v", acceptToken[0], token)
			result, _ := json.Marshal(entity.HttpResult{Status: false, Code: "1001", Message: "请求头 Authorization 校验失败。"})
			_, _ = fmt.Fprintf(w, string(result))
			return
		}

		// 如果通过校验，继续处理下一个处理程序
		next.ServeHTTP(w, r)
	})
}
