import crypto from 'node:crypto';

export function assertStrongPassword(password, { minLength = 12, label = 'Parola' } = {}) {
  const text = String(password || '');
  if (text.length < minLength) throw Object.assign(new Error(`${label} en az ${minLength} karakter olmalıdır.`), { code: 'PASSWORD_WEAK', status: 400 });
  if (!/[A-ZÇĞİÖŞÜ]/u.test(text) || !/[a-zçğıöşü]/u.test(text) || !/\d/.test(text) || !/[^\p{L}\p{N}]/u.test(text)) {
    throw Object.assign(new Error(`${label} büyük harf, küçük harf, rakam ve özel karakter içermelidir.`), { code: 'PASSWORD_WEAK', status: 400 });
  }
  return text;
}

export function hashPassword(password, salt = crypto.randomBytes(16), params = { N: 32768, r: 8, p: 1, dkLen: 32 }) {
  const derived = crypto.scryptSync(String(password), salt, params.dkLen, {
    N: params.N, r: params.r, p: params.p, maxmem: 128 * 1024 * 1024
  });
  return {
    hash: derived.toString('base64url'),
    salt: salt.toString('base64url'),
    params
  };
}

export function verifyPassword(password, row) {
  if (!row?.password_hash || !row?.password_salt) return false;
  let params;
  try { params = JSON.parse(row.password_params_json || '{}'); } catch { return false; }
  const calculated = hashPassword(password, Buffer.from(row.password_salt, 'base64url'), params).hash;
  const left = Buffer.from(calculated);
  const right = Buffer.from(String(row.password_hash));
  return left.length === right.length && crypto.timingSafeEqual(left, right);
}
