// src/auth.js
// Password hashing with Node's built-in crypto.scrypt — no external
// dependency (bcrypt) needed, keeping this friendly to shared cPanel hosting.
const crypto = require('crypto');

function hashPassword(password) {
  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto.scryptSync(password, salt, 64).toString('hex');
  return `${salt}:${hash}`;
}

function verifyPassword(password, stored) {
  const [salt, hash] = String(stored).split(':');
  if (!salt || !hash) return false;
  const check = crypto.scryptSync(password, salt, 64).toString('hex');
  const a = Buffer.from(hash, 'hex');
  const b = Buffer.from(check, 'hex');
  if (a.length !== b.length) return false;
  return crypto.timingSafeEqual(a, b);
}

// Returns { ok, reasons[] }. Requires 10+ chars and at least three of the
// four character classes (upper, lower, number, symbol) — strong enough to
// resist offline guessing without being so strict it locks real admins out.
function checkPasswordStrength(password) {
  const reasons = [];
  const value = String(password || '');
  if (value.length < 10) reasons.push('Use at least 10 characters.');
  const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].filter((re) => re.test(value)).length;
  if (classes < 3) reasons.push('Mix upper/lowercase letters, numbers, and a symbol.');
  const common = ['password', 'changeme', '12345678', 'qwertyui', 'admin123', 'letmein11'];
  if (common.some((c) => value.toLowerCase().includes(c))) reasons.push("Avoid common or guessable passwords.");
  return { ok: reasons.length === 0, reasons };
}

module.exports = { hashPassword, verifyPassword, checkPasswordStrength };
