import crypto from 'crypto';

// Validate the API key from request headers
export function validateApiToken(timestamp: string, apiToken: string, origin: string, apiSecret: string): boolean {
  // Get timestamp from headers
  if (!timestamp) {
    return false;
  }

  // Check if timestamp is within a valid window (10 seconds)
  const requestTime = parseInt(timestamp, 10);
  const currentTime = Math.floor(Date.now() / 1000);
  if (Math.abs(currentTime - requestTime) > 10) {
    return false;
  }

  // Get and validate the provided token
  const providedToken = apiToken;
  if (!providedToken) {
    return false;
  }

  // Compute expected token: HMAC(timestamp + origin, API_SECRET)
  const data = `${timestamp}${origin || ''}`;
  const expectedToken = crypto.createHmac('sha256', apiSecret).update(data).digest('hex');

  try {
    return crypto.timingSafeEqual(Buffer.from(providedToken), Buffer.from(expectedToken));
  } catch (e) {
    // Handle potential buffer length mismatch
    return false;
  }
}
