import crypto from 'node:crypto';

const KEY_PREFIX = 'zy_';

/**
 * Generate a new cryptographically secure API key.
 * Format: zy_<32 hex chars> (16 random bytes)
 */
export function generateApiKey(): string {
  const randomHex = crypto.randomBytes(16).toString('hex');
  return `${KEY_PREFIX}${randomHex}`;
}

/**
 * Compute the HMAC-SHA256 verifier hash of an API key using the system pepper.
 */
export function computeKeyVerifier(apiKey: string, pepper: string): string {
  return crypto.createHmac('sha256', pepper).update(apiKey).digest('hex');
}

/**
 * Timing-safe comparison of provided API key against stored HMAC-SHA256 verifier.
 */
export function verifyApiKey(providedKey: string, storedHash: string, pepper: string): boolean {
  if (!providedKey || !storedHash) {
    return false;
  }

  const computedHash = computeKeyVerifier(providedKey, pepper);
  const bufA = Buffer.from(computedHash, 'utf8');
  const bufB = Buffer.from(storedHash, 'utf8');

  if (bufA.length !== bufB.length) {
    return false;
  }

  return crypto.timingSafeEqual(bufA, bufB);
}

/**
 * Safely extract the visible key prefix for audit logs without revealing the secret portion.
 * e.g. "zy_a1b2c3d4..." -> "zy_a1b2"
 */
export function getMaskedApiKeyPrefix(apiKey: string): string {
  if (!apiKey.startsWith(KEY_PREFIX)) {
    return 'invalid_key';
  }
  return apiKey.slice(0, 7) + '...';
}

