/**
 * Extracts the real client IP and user-agent from an incoming Next.js route
 * request and returns them as headers to forward to the upstream Rails API.
 *
 * Cloudflare and other load-balancers set x-real-ip (or x-forwarded-for) on
 * inbound requests before they reach the Next.js function. Without this, the
 * Rails API sees the Next.js server IP instead of the real browser IP, which
 * produces inaccurate server-side CAPI signals.
 *
 * Convention: forwarded as X-Real-Client-IP / X-Real-Client-UA so that Rails
 * can read them explicitly without conflicting with its own proxy middleware.
 */
export function clientContextHeaders(request: Request): Record<string, string> {
  const ip =
    request.headers.get('x-real-ip') ||
    request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
  const ua = request.headers.get('user-agent');
  const headers: Record<string, string> = {};
  if (ip) headers['X-Real-Client-IP'] = ip;
  if (ua) headers['X-Real-Client-UA'] = ua;
  return headers;
}
