import { createHmac, timingSafeEqual } from 'crypto';

export type WebhookVerifyOptions = {
  secret: string;
  payload: string;
  signature: string;
  algorithm?: 'sha256' | 'sha512';
  encoding?: 'hex' | 'base64';
};

export function computeWebhookSignature(
  secret: string,
  payload: string,
  algorithm: 'sha256' | 'sha512' = 'sha256',
  encoding: 'hex' | 'base64' = 'hex'
): string {
  return createHmac(algorithm, secret).update(payload, 'utf8').digest(encoding);
}

export function verifyWebhookSignature(options: WebhookVerifyOptions): boolean {
  const { secret, payload, signature, algorithm = 'sha256', encoding = 'hex' } = options;
  if (!secret || !signature) return false;

  const expected = computeWebhookSignature(secret, payload, algorithm, encoding);
  const provided = signature.startsWith('sha256=') || signature.startsWith('sha512=')
    ? signature.split('=')[1] ?? ''
    : signature;

  try {
    const a = Buffer.from(expected, encoding);
    const b = Buffer.from(provided, encoding);
    if (a.length !== b.length) return false;
    return timingSafeEqual(a, b);
  } catch {
    return false;
  }
}
