/**
 * API签名工具
 * 用于生成API请求的数字签名
 */

// 配置项
const SIGNATURE_CONFIG = {
  secretKey: 'default_secret_key', // 与后端保持一致
  appId: 'ruoyi-frontend', // 应用ID
  timestampTolerance: 300 // 时间戳容忍度（秒）
}

/**
 * 生成随机字符串
 * @param {number} length 长度
 * @returns {string} 随机字符串
 */
function generateNonce(length = 16) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

/**
 * 构建签名字符串
 * @param {string} method HTTP方法
 * @param {string} path 请求路径
 * @param {Object} params 查询参数
 * @param {string} timestamp 时间戳
 * @param {string} nonce 随机数
 * @param {string} appId 应用ID
 * @returns {string} 签名字符串
 */
function buildSignatureString(method, path, params, timestamp, nonce, appId) {
  let signatureString = method.toUpperCase() + '\n'
  signatureString += path + '\n'
  
  // 处理查询参数（按字母顺序排序）
  if (params && Object.keys(params).length > 0) {
    const sortedParams = Object.keys(params).sort().map(key => `${key}=${params[key]}`).join('&')
    signatureString += sortedParams
  }
  signatureString += '\n'
  
  signatureString += timestamp + '\n'
  signatureString += nonce + '\n'
  signatureString += appId
  
  return signatureString
}

/**
 * 计算SHA256哈希
 * @param {string} data 要哈希的数据
 * @returns {Promise<string>} 哈希值（十六进制）
 */
async function sha256(data) {
  const encoder = new TextEncoder()
  const dataBuffer = encoder.encode(data)
  const hashBuffer = await crypto.subtle.digest('SHA-256', dataBuffer)
  const hashArray = Array.from(new Uint8Array(hashBuffer))
  return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
}

/**
 * 计算签名
 * @param {string} signatureString 签名字符串
 * @returns {Promise<string>} 签名值
 */
async function calculateSignature(signatureString) {
  const dataToSign = signatureString + '\n' + SIGNATURE_CONFIG.secretKey
  return await sha256(dataToSign)
}

/**
 * 生成API签名头
 * @param {string} method HTTP方法
 * @param {string} url 完整URL
 * @returns {Promise<Object>} 签名头对象
 */
export async function generateSignatureHeaders(method, url) {
  try {
    // 解析URL
    const urlObj = new URL(url, window.location.origin)
    const path = urlObj.pathname
    
    // 解析查询参数
    const params = {}
    urlObj.searchParams.forEach((value, key) => {
      params[key] = value
    })
    
    // 生成签名参数
    const timestamp = Math.floor(Date.now() / 1000).toString()
    const nonce = generateNonce()
    const appId = SIGNATURE_CONFIG.appId
    
    // 构建签名字符串
    const signatureString = buildSignatureString(method, path, params, timestamp, nonce, appId)
    
    // 计算签名
    const signature = await calculateSignature(signatureString)
    
    return {
      'X-Signature': signature,
      'X-Timestamp': timestamp,
      'X-Nonce': nonce,
      'X-App-Id': appId
    }
  } catch (error) {
    console.error('生成API签名失败:', error)
    return {}
  }
}

/**
 * 检查是否需要签名验证
 * @param {string} url 请求URL
 * @returns {boolean} 是否需要签名
 */
export function requiresSignature(url) {
  const signatureRequiredPaths = [
    '/api/credit/financing',
    '/api/payment',
    '/api/blockchain'
  ]
  
  return signatureRequiredPaths.some(path => url.includes(path))
}