/**
 * Generate a correlation ID — 16 random bytes, base64url-encoded (22 chars
 * after stripping padding). Same shape as `RequestIdSchema`.
 *
 * Uses `globalThis.crypto.getRandomValues` so it works in Bun, Node ≥19,
 * and browsers without any platform-specific imports.
 */
export function generateRequestId(): string {
  const buf = new Uint8Array(16);
  globalThis.crypto.getRandomValues(buf);
  return base64UrlEncode(buf);
}

/** Same as `generateRequestId` — distinct name for callsite clarity. */
export function generateIdempotencyKey(): string {
  return generateRequestId();
}

export function base64UrlEncode(bytes: Uint8Array): string {
  let bin = '';
  for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
  return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

export function base64UrlDecode(s: string): Uint8Array {
  const padded = s.replace(/-/g, '+').replace(/_/g, '/');
  const pad = padded.length % 4 === 0 ? '' : '='.repeat(4 - (padded.length % 4));
  const bin = atob(padded + pad);
  const out = new Uint8Array(bin.length);
  for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
  return out;
}
