import crypto from 'node:crypto';
/**
 * Harici ajan/otomasyon imzası:
 *   X-Parsel-Timestamp: unix saniye
 *   X-Parsel-Signature: hex(HMAC_SHA256(ORDER_WEBHOOK_SECRET, `${timestamp}.${rawBody}`))
 * 5 dakikadan eski istekler reddedilir.
 */
export function signAgent(body: string, ts = Math.floor(Date.now() / 1000), secret = process.env.ORDER_WEBHOOK_SECRET || '') {
  return { ts: String(ts), sig: crypto.createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex') };
}
export function verifyAgent(req: Request, rawBody: string) {
  const secret = process.env.ORDER_WEBHOOK_SECRET;
  if (!secret) return false;
  const ts = req.headers.get('x-parsel-timestamp') || '';
  const sig = req.headers.get('x-parsel-signature') || '';
  const n = Number(ts);
  if (!n || Math.abs(Date.now() / 1000 - n) > 300) return false;
  const exp = signAgent(rawBody, n, secret).sig;
  const a = Buffer.from(sig, 'hex'), b = Buffer.from(exp, 'hex');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
