package com.bonus.canteen.core.auth.oauth.util;

import cn.hutool.core.util.ObjectUtil;
import javax.servlet.http.HttpServletRequest;
import com.bonus.canteen.core.common.utils.SpringContextHolder;
import com.bonus.common.houqin.framework.secure.SecureProperties;
import com.bonus.canteen.core.config.SmUtils;
import org.springframework.context.annotation.Lazy;
import com.bonus.common.houqin.framework.secure.WebContext;
import java.util.TreeMap;

public class OAuthUtil {
   private static final String HEADER_SECURITY_TENANT_ID = "X-Security-Tenant-Id";
   private static final String HEADER_SECURITY_TOKEN = "X-Security-Token";
   @Lazy
   private static final SecureProperties secureProperties = (SecureProperties) SpringContextHolder.getBean(SecureProperties.class);

   private OAuthUtil() {
   }

   public static String responseSetSecurityTokenSign(Long merchantId, String token) {
      TreeMap<String, String> needSignMap = new TreeMap();
      String securityTokenSign = null;
      if (WebContext.get().getRequest().isPresent()) {
         String encryptKey = ((HttpServletRequest)WebContext.get().getRequest().get()).getHeader(secureProperties.getSecurity().getServerEncryptedClientKeyHeaderName());
         if (ObjectUtil.isNotNull(encryptKey)) {
            if (ObjectUtil.isNotNull(merchantId)) {
               needSignMap.put("X-Security-Tenant-Id", String.valueOf(merchantId));
            }

            needSignMap.put("X-Security-Token", token);
            String serverEncryptedClientKey = ((HttpServletRequest)WebContext.get().getRequest().get()).getHeader(secureProperties.getSecurity().getServerEncryptedClientKeyHeaderName());
            String clientKey = SmUtils.decryptBySm4WithServerKey(serverEncryptedClientKey);
            securityTokenSign = SmUtils.signAuthTokenBySm3(needSignMap, clientKey);
         }
      }

      return securityTokenSign;
   }
}
