// A browser has no API to read its own public IP — the only place
// that's actually visible is the request as it arrives at this app's
// own server, forwarded by whatever reverse proxy/load balancer sits
// in front of it in production. Used by proxy routes that need to
// report the real client IP to the Go backend (verify-login-otp,
// register) instead of a hardcoded placeholder.
export function getClientIp(request: Request): string {
  const forwardedFor = request.headers.get("x-forwarded-for");

  if (forwardedFor) {
    // Left-most entry is the original client; anything after it was
    // appended by intermediate proxies.
    const first = forwardedFor.split(",")[0]?.trim();
    if (first) return first;
  }

  const realIp = request.headers.get("x-real-ip");
  if (realIp) return realIp.trim();

  return "";
}
