import CryptoJS from 'crypto-js'

/**
 * HMAC-SHA256 签名工具
 * 签名规则：排序的 query params + nonce + timestamp，用 & 拼接
 * POST JSON body 不参与签名
 */
export function signRequest(orgId, appSecret, queryParams = {}) {
  const timestamp = String(Date.now())
  const nonce = Math.random().toString(36).substring(2, 15) + Date.now().toString(36)

  // Build sign string: sorted params + nonce + timestamp
  const allParams = { ...queryParams, nonce, timestamp }
  const sorted = Object.keys(allParams).sort()
  const signStr = sorted.map(k => `${k}=${allParams[k]}`).join('&')

  const signature = CryptoJS.HmacSHA256(signStr, appSecret).toString(CryptoJS.enc.Hex)

  return {
    'X-App-Key': orgId,
    'X-Timestamp': timestamp,
    'X-Nonce': nonce,
    'X-Signature': signature
  }
}
