import { createHmac, timingSafeEqual } from "node:crypto";
// Call with the ORIGINAL body bytes; do not JSON.parse/stringify before checking.
// The application must persist event IDs transactionally before processing them.
export function verifyWebhook(
  rawBody,
  timestamp,
  signature,
  secret,
  nowSeconds = Date.now() / 1000,
) {
  if (
    !secret ||
    !/^\d{10}$/.test(timestamp) ||
    Math.abs(nowSeconds - Number(timestamp)) > 300 ||
    !/^sha256=[a-f0-9]{64}$/.test(signature) ||
    Buffer.byteLength(rawBody) > 8192
  )
    return false;
  const expected =
    "sha256=" +
    createHmac("sha256", secret)
      .update(timestamp + ".")
      .update(rawBody)
      .digest("hex");
  return timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}
