package com.yeejoin.amos.boot.module.jxiop.biz.feign;

import com.yeejoin.amos.component.robot.AmosRequestContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fengwang
 * @date 2022-07-28.
 */

public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {

    @Autowired
    AmosRequestContext amosAuth;
    public FeignBasicAuthRequestInterceptor() {

    }

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();

            /* Get token from header */
            String authToken = request.getHeader("token");
            /* If token not found get it from request parameter */
            if (StringUtils.isBlank(authToken)) {
                authToken = request.getHeader("X-Access-Token");
            }
            template.header("X-Access-Token", authToken);
            template.header("token", authToken);
            template.header("appKey", request.getHeader("appKey"));
            template.header("product", request.getHeader("product"));
            template.header("clientType", "feignClient");
            //User-Agent for core
            template.header("User-Agent", "java");
        }else {
            template.header("X-Access-Token", amosAuth.getToken());
            template.header("token", amosAuth.getToken());
            template.header("appKey", amosAuth.getAppKey());
            template.header("product", amosAuth.getProduct());
            template.header("clientType", "feignClient");
            //User-Agent for core
            template.header("User-Agent", "java");
        }
    }
}

