import crypto from 'crypto';

function safeCompare(a: string, b: string): boolean {
  const bufA = Buffer.from(a);
  const bufB = Buffer.from(b);
  if (bufA.length !== bufB.length) {
    crypto.timingSafeEqual(bufA, bufA);
    return false;
  }
  return crypto.timingSafeEqual(bufA, bufB);
}

export function verifyN8nSignature(signature: string | null): boolean {
  if (!signature) return false;
  const secret = process.env.N8N_WEBHOOK_SECRET || '';
  const secretDev = process.env.N8N_WEBHOOK_SECRET_DEV || '';
  
  if (secret && safeCompare(signature, secret)) return true;
  if (secretDev && safeCompare(signature, secretDev)) return true;
  
  return false;
}
