import crypto from "node:crypto";
import { promisify } from "node:util";

const scrypt = promisify(crypto.scrypt);

export async function hashPassword(password: string) {
  if (password.length < 12) throw new Error("Le mot de passe doit contenir au moins 12 caractères.");
  const salt = crypto.randomBytes(16);
  const derived = await scrypt(password, salt, 64) as Buffer;
  return `scrypt$${salt.toString("base64url")}$${derived.toString("base64url")}`;
}

export async function verifyPassword(password: string, stored: string) {
  const [algorithm, saltValue, hashValue] = stored.split("$");
  if (algorithm !== "scrypt" || !saltValue || !hashValue) return false;
  const expected = Buffer.from(hashValue, "base64url");
  const derived = await scrypt(password, Buffer.from(saltValue, "base64url"), expected.length) as Buffer;
  return expected.length === derived.length && crypto.timingSafeEqual(expected, derived);
}
