/**
 * Secure password hashing using Node.js built-in crypto (scrypt)
 * No external packages required.
 */
const crypto = require('crypto');

const SALT_LENGTH = 32;
const KEY_LENGTH = 64;

/**
 * Hash a plaintext password. Returns a string like: "salt:hash" (both hex).
 */
function hashPassword(password) {
  const salt = crypto.randomBytes(SALT_LENGTH).toString('hex');
  const hash = crypto.scryptSync(password, salt, KEY_LENGTH).toString('hex');
  return `${salt}:${hash}`;
}

/**
 * Verify a plaintext password against a stored "salt:hash" string.
 */
function verifyPassword(password, stored) {
  try {
    const [salt, storedHash] = stored.split(':');
    if (!salt || !storedHash) return false;
    const hash = crypto.scryptSync(password, salt, KEY_LENGTH).toString('hex');
    // Constant-time comparison to prevent timing attacks
    return crypto.timingSafeEqual(
      Buffer.from(hash, 'hex'),
      Buffer.from(storedHash, 'hex')
    );
  } catch (err) {
    return false;
  }
}

module.exports = { hashPassword, verifyPassword };
