import { isIP } from "node:net";

/**
 * The visitor's IP from an X-Forwarded-For chain.
 *
 * If a reverse proxy in front of the app (nginx, load balancer) appended its own
 * entry, the rightmost one is the address that proxy saw, and the only one a client
 * can't forge. When the app is exposed directly, Next fills the header with the
 * connecting address (it never overwrites a client-supplied one), so put a reverse
 * proxy in front in production.
 *
 * Returns undefined when there is no valid IPv4/IPv6 address.
 */
export function clientIpFrom(forwardedFor: string | null | undefined): string | undefined {
  const ip = (forwardedFor ?? "")
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean)
    .pop()
    ?.replace(/^::ffff:/, "");
  return ip && isIP(ip) ? ip : undefined;
}
