package org.lingniu.idp.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.DigestUtils;

// 设备指纹工具
public class DeviceFingerprintUtil {
    
    public static String generateFingerprint(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        String acceptLanguage = request.getHeader("Accept-Language");
        String acceptEncoding = request.getHeader("Accept-Encoding");
        String ipAddress = getClientIp(request);
        
        String fingerprintSource = userAgent + "|" + acceptLanguage + "|" + acceptEncoding + "|" + ipAddress;
        return DigestUtils.md5DigestAsHex(fingerprintSource.getBytes());
    }
    
    private static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.split(",")[0].trim();
    }
}