package service

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"sort"
)

const (
	reqAccessPopToken     = "access-pop-token"
	reqAccessPopTimestamp = "access-pop-timestrap"
	reqAccessPopNonceStr  = "access-pop-noncestr"
)

func GenerateSignature(token, timestamp, nonceStr, appSecret string) (string, error) {
	// 使用 Go的map 和一个额外的 keys 列表保持顺序
	treeMap := make(map[string]string)
	keys := []string{
		reqAccessPopToken,
		reqAccessPopTimestamp,
		reqAccessPopNonceStr,
	}
	treeMap[reqAccessPopToken] = token
	treeMap[reqAccessPopTimestamp] = timestamp
	treeMap[reqAccessPopNonceStr] = nonceStr

	sysSignature, err := GenHMAC(treeMap, keys, appSecret)
	if err != nil {
		return "", fmt.Errorf("failed to generate HMAC: %v", err)
	}

	return sysSignature, nil
}

//生成签名
func GenHMAC(data map[string]string, keys []string, key string) (string, error) {
	// 对 keys 进行排序以确保顺序
	sort.Strings(keys)

	// 构建 JSON 字符串
	dataMapOrdered := make(map[string]string)
	for _, k := range keys {
		dataMapOrdered[k] = data[k]
	}
	jsonData, err := json.Marshal(dataMapOrdered)
	if err != nil {
		return "", err
	}

	// 创建 hmac
	h := hmac.New(sha256.New, []byte(key))
	if _, err := h.Write([]byte(jsonData)); err != nil {
		return "", err
	}
	signature := hex.EncodeToString(h.Sum(nil))
	return signature, nil

}
