package com.sikey.wa04.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.sikey.wa04.common.constants.HeaderConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

public class FeignRequestInterceptor implements RequestInterceptor {
    private static final String[] INCLUDE_HEADERS = new String[]{
            HeaderConstant.REQUEST_ID,
            HeaderConstant.SYSTEM,
            HeaderConstant.SYSTEM_VERSION,
            HeaderConstant.SOFTWARE_VERSION,
            HeaderConstant.MANUFACTURER,
            HeaderConstant.TIME_ZONE,
            HeaderConstant.TIMESTAMP,
            // HeaderConstant.AUTHORIZATION,
            "authorization"
    };

    @Override
    public void apply(RequestTemplate template) {
        Map<String, String> headers = getHeaders();
        headers.forEach(template::header);
    }

    /**
     * 获取请求头
     *
     * @return 请求头
     */
    private Map<String, String> getHeaders() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Map<String, String> headers = new LinkedHashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            if (Arrays.stream(INCLUDE_HEADERS)
                    .anyMatch(includeHeader -> StrUtil.equalsIgnoreCase(includeHeader, key))) {
                String value = request.getHeader(key);
                headers.put(key, value);
            }
        }
        return headers;
    }
}
