import crypto from "crypto";

/**
 * Smartcar webhook VERIFY handshake: HMAC-SHA256(secret, challenge) as lowercase hex.
 * @see https://smartcar.com/docs/integrations/webhooks/callback-verification
 *
 * Older `smartcar` npm releases omit `hashChallenge`; this matches documented behavior.
 */
export function hashSmartcarWebhookChallenge(secret: string, challenge: string): string {
  return crypto
    .createHmac("sha256", secret.trim())
    .update(challenge, "utf8")
    .digest("hex");
}

/**
 * Verify `SC-Signature` header on incoming webhook payloads.
 * HMAC-SHA256(managementToken, rawBody) must equal the header value.
 * Uses timing-safe comparison to prevent timing attacks.
 * @see https://smartcar.com/docs/integrations/webhooks/payload-verification
 */
export function verifySmartcarPayloadSignature(
  managementToken: string,
  scSignature: string,
  rawBody: string,
): boolean {
  const expected = crypto
    .createHmac("sha256", managementToken)
    .update(rawBody)
    .digest("hex");
  if (expected.length !== scSignature.length) return false;
  return crypto.timingSafeEqual(
    Uint8Array.from(Buffer.from(expected)),
    Uint8Array.from(Buffer.from(scSignature)),
  );
}
