import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';

export function generateSecureToken(bytes = 32): string {
  return randomBytes(bytes).toString('base64url');
}

export function hashToken(token: string): string {
  return createHash('sha256').update(token).digest('hex');
}

export function verifyTokenHash(token: string, hashed: string): boolean {
  const computed = hashToken(token);
  const computedBuffer = Buffer.from(computed, 'hex');
  const hashedBuffer = Buffer.from(hashed, 'hex');

  if (computedBuffer.length !== hashedBuffer.length) {
    return false;
  }

  return timingSafeEqual(computedBuffer, hashedBuffer);
}
