/**
 * sha256 helpers — for opaque-token hashing (step 4) and IP pseudonymisation.
 * PLANNING.md §9: only `sha256(ip + IP_HASH_SALT)` is ever stored, never a raw
 * IP — enough for rate limiting and abuse forensics, not personal data at rest.
 */
import { createHash } from 'node:crypto';
import { env } from '../env';

export function sha256Hex(input: string | Buffer): string {
  const h = createHash('sha256');
  return (typeof input === 'string' ? h.update(input, 'utf8') : h.update(input)).digest('hex');
}

/** Pseudonymised client IP for storage and rate-limit keys. */
export function hashIp(ip: string): string {
  return sha256Hex(`${ip}${env.IP_HASH_SALT}`);
}

/**
 * Hash for an opaque refresh- or reset-token before it is stored (the raw value
 * is never persisted). Peppered with JWT_REFRESH_SECRET so a database leak alone
 * cannot forge a valid token. Output is 64 hex chars — matches `token_hash CHAR(64)`.
 */
export function hashToken(raw: string): string {
  return sha256Hex(`${raw}${env.JWT_REFRESH_SECRET}`);
}
