package io.github.shirainbown.sharelink.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * Resolves the client IP address of a request: the first {@code X-Forwarded-For} segment
 * wins, falling back to the remote address of the connection.
 */
public final class IpUtils {

    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private IpUtils() {
    }

    /**
     * Resolves the client IP address.
     *
     * @param request the current request
     * @return the client IP, or {@code null} when neither a forwarded header nor a remote
     * address is available
     */
    public static String clientIp(ServerHttpRequest request) {
        var forwardedFor = request.getHeaders().getFirst(X_FORWARDED_FOR);
        if (StringUtils.isNotBlank(forwardedFor)) {
            return forwardedFor.split(",")[0].trim();
        }
        var remoteAddress = request.getRemoteAddress();
        if (remoteAddress == null) {
            return null;
        }
        var address = remoteAddress.getAddress();
        return address != null ? address.getHostAddress() : remoteAddress.getHostString();
    }
}
