package com.changhu.support.interceptor;

import com.changhu.common.annotation.CheckOpenApi;
import com.changhu.common.exception.MessageException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 20252
 * @createTime 2024/10/9 下午5:05
 * @desc OpenApiInterceptor...
 */
@Slf4j
public class OpenApiInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String header = request.getHeader("X-API-KEY");
        log.info("apiKey:{} {} 请求:{}", header, LocalDateTime.now(), request.getRequestURI());
        if (handler instanceof HandlerMethod handlerMethod) {
            CheckOpenApi methodAnnotation = handlerMethod.getMethodAnnotation(CheckOpenApi.class);
            if (methodAnnotation != null) {
                List<String> openApiKeys = methodAnnotation.value().getOpenApiKeys();
                if (!openApiKeys.contains(header)) {
                    throw new MessageException("openApiKey error!");
                }
            }
        }
        return true;
    }
}
