import { bytesToHex } from '@/lib/encoding.js';

/**
 * IP extraction + hashing helpers.
 *
 * Consolidates auth/get-ip.ts and auth/ip-hash.ts.
 */

/**
 * Extract the real client IP from a Cloudflare Workers request.
 * Order: cf-connecting-ip → x-forwarded-for (first hop) → fallback.
 */
export function getIp(request: Request): string {
  return (
    request.headers.get('cf-connecting-ip') ??
    request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ??
    '0.0.0.0'
  );
}

/**
 * SHA-256 digest of an IP string (hex-encoded).
 * Used as an anonymous bucket key — never log the raw IP.
 */
export async function hashIp(ip: string): Promise<string> {
  const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(ip));
  return bytesToHex(buf);
}
