function getClientIp(req) {
  const forwarded = req.headers["x-forwarded-for"]
  if (typeof forwarded === "string" && forwarded.trim()) {
    return forwarded.split(",")[0].trim()
  }
  if (Array.isArray(forwarded) && forwarded.length > 0) {
    return String(forwarded[0]).trim()
  }

  const realIp = req.headers["x-real-ip"]
  if (typeof realIp === "string" && realIp.trim()) return realIp.trim()
  if (Array.isArray(realIp) && realIp.length > 0) return String(realIp[0]).trim()

  if (req.ip) return String(req.ip)
  return null
}

module.exports = { getClientIp }
