// Shared-secret auth for customer-lookup endpoints that expose PII.
// The acot-phone-server sends `x-acot-api-key` on every request; we compare
// against ACOT_PHONE_API_KEY from the environment using timing-safe comparison.

import crypto from 'node:crypto';

export function requirePhoneApiKey(req, res, next) {
  const expected = process.env.ACOT_PHONE_API_KEY;
  if (!expected) {
    console.error('ACOT_PHONE_API_KEY not configured; rejecting all requests');
    return res.status(503).json({ success: false, error: 'auth_not_configured' });
  }

  const provided = req.get('x-acot-api-key') || '';
  const expectedBuf = Buffer.from(expected);
  const providedBuf = Buffer.from(provided);

  if (
    providedBuf.length !== expectedBuf.length ||
    !crypto.timingSafeEqual(providedBuf, expectedBuf)
  ) {
    return res.status(401).json({ success: false, error: 'unauthorized' });
  }

  next();
}
