package com.pharmacopoeia.util;

import jakarta.servlet.http.HttpServletRequest;

public final class IpUtils {

    private IpUtils() {}

   public static String getClientIp(HttpServletRequest request) {
        // X-Forwarded-For: client, proxy1, proxy2, ...
        String xff = request.getHeader("X-Forwarded-For");
        if (xff != null && !xff.isBlank()) {
            for (String part : xff.split(",")) {
                String ip = part.trim();
                if (!ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                }
            }
        }
        for (String header : new String[]{"X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"}) {
            String val = request.getHeader(header);
            if (val != null && !val.isBlank() && !"unknown".equalsIgnoreCase(val.trim())) {
                return val.trim();
            }
        }
        return request.getRemoteAddr();
   }
}
