package com.ruoyi.aicall.utils;

import com.ruoyi.cc.service.ICcParamsService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

@Slf4j
public class ClientIpCheck {

    public static Boolean checkIp(HttpServletRequest request){
        String clientIp = getClientIp(request);
        log.info("get client ip:{}", clientIp);
        ICcParamsService ccParamsService = SpringUtils.getBean(ICcParamsService.class);
        String whiteIpList = ccParamsService.getParamValueByCode("api-client-white-ips", "");
        if (StringUtils.isNotEmpty(whiteIpList)) {
            for (String ip: whiteIpList.split(",")) {
                if (ip.equals(clientIp)) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    public static String getClientIp(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "X-Real-IP",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };
        for (String h : headers) {
            String value = request.getHeader(h);
            if (value != null && !value.isEmpty() && !"unknown".equalsIgnoreCase(value)) {
                return value.split(",")[0].trim();
            }
        }
        return request.getRemoteAddr();
    }
}
