import crypto from 'node:crypto'

export function hmacSha256Hex(secret: string, payload: string): string {
  return crypto.createHmac('sha256', secret).update(payload).digest('hex')
}

export function buildPrivateWsAuth(apiKey: string, secret: string): [string, number, string] {
  const expires = Date.now() + 10_000
  const signature = hmacSha256Hex(secret, `GET/realtime${expires}`)
  return [apiKey, expires, signature]
}

/**
 * Build Bybit V5 auth headers for REST requests.
 * Both DemoExecutor and BybitRestClient use identical signing logic;
 * this shared function eliminates duplication.
 */
export function buildBybitAuthHeaders(
  apiKey: string,
  apiSecret: string,
  recvWindow: number,
  payloadStr: string   // queryString for GET, JSON body for POST
): Record<string, string> {
  const timestamp = Date.now().toString()
  const toSign    = `${timestamp}${apiKey}${recvWindow}${payloadStr}`
  const signature = hmacSha256Hex(apiSecret, toSign)
  return {
    'X-BAPI-SIGN-TYPE': '2',
    'X-BAPI-SIGN':       signature,
    'X-BAPI-API-KEY':    apiKey,
    'X-BAPI-TIMESTAMP':  timestamp,
    'X-BAPI-RECV-WINDOW': String(recvWindow)
  }
}
