import crypto from 'crypto';

async function hashPassword(password) {
  return new Promise((resolve, reject) => {
    const salt = crypto.randomBytes(16).toString('hex');
    crypto.scrypt(password, salt, 64, (err, derivedKey) => {
      if (err) reject(err);
      resolve(salt + ':' + derivedKey.toString('hex'));
    });
  });
}

async function verifyPassword(password, hash) {
  return new Promise((resolve, reject) => {
    const [salt, key] = hash.split(':');
    crypto.scrypt(password, salt, 64, (err, derivedKey) => {
      if (err) { reject(err); return; }
      try {
        const storedKey = Buffer.from(key, 'hex');
        if (storedKey.length !== derivedKey.length) { resolve(false); return; }
        resolve(crypto.timingSafeEqual(storedKey, derivedKey));
      } catch {
        resolve(false);
      }
    });
  });
}

function generateToken(length = 32) {
  return crypto.randomBytes(length).toString('hex');
}

function generateId() {
  return crypto.randomUUID();
}

export { hashPassword, verifyPassword, generateToken, generateId };
