package com.m2pool.common.security.interceptor;

import com.m2pool.common.core.constant.OpenApiKeyConstants;
import com.m2pool.common.core.context.OpenApiContextHolder;
import com.m2pool.common.core.utils.ServletUtils;
import com.m2pool.common.core.utils.StringUtils;
import com.m2pool.common.core.utils.ip.IpUtils;
import com.m2pool.common.security.auth.ApiUtil;
import com.m2pool.common.security.utils.OpenApiUtils;
import com.m2pool.system.api.model.OpenApiKeyInfo;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description 自定义请求头拦截器，将请求头数据封装到线程变量中方便后续获取使用
 * 同时获取当前用户有效时间并刷新有效期
 * @Date 2024/6/13 20:29
 * @Author dy
 */
public class OpenApiHeaderInterceptor implements AsyncHandlerInterceptor {

    private static final Map<String, AtomicInteger> limitCounter = new ConcurrentHashMap<>();
    private static final int MAX_REQUESTS_SECOND = 5;
    private static final int MAX_REQUESTS_DAY = 5000;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("调用Oapi拦截器,路径:"+request.getRequestURI());
        System.out.println(IpUtils.getIpAddr(request));
        if(!(handler instanceof HandlerMethod)){
            return true;

        }

        //System.out.println("OpenApiHeaderInterceptor.preHandle 开始赋值");

        OpenApiContextHolder.setApiUser(ServletUtils.getHeader(request, OpenApiKeyConstants.API_USER));
        OpenApiContextHolder.setApiIp(ServletUtils.getHeader(request,OpenApiKeyConstants.API_IP));
        OpenApiContextHolder.setApiKey(ServletUtils.getHeader(request,OpenApiKeyConstants.API_KEY));

        String apiKey = OpenApiUtils.getApiKey();
        if(StringUtils.isNotEmpty(apiKey)){

            OpenApiKeyInfo apiKeyInfo = ApiUtil.getApiKeyInfo(apiKey);
            if(StringUtils.isNotNull(apiKeyInfo)){

                //验证当前用户有效时间
                ApiUtil.verifyApiKeyExpire(apiKeyInfo);
                OpenApiContextHolder.set(OpenApiKeyConstants.API_KEY_INFO,apiKeyInfo);
            }

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        OpenApiContextHolder.remove();

    }
}
