package com.haobang.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * API-KEY认证拦截器
 */
@Component
public class ApiKeyInterceptor implements HandlerInterceptor {

    @Value("${interlocking.api-key:}")
    private String configuredApiKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放行CORS预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        String requestApiKey = request.getHeader("X-API-KEY");
        
        // 如果配置了API-KEY，则进行校验
        if (configuredApiKey != null && !configuredApiKey.isEmpty()) {
            if (requestApiKey == null || requestApiKey.isEmpty()) {
                sendUnauthorized(response, "API-KEY header is missing");
                return false;
            }
            
            if (!configuredApiKey.equals(requestApiKey)) {
                sendUnauthorized(response, "Invalid API-KEY");
                return false;
            }
        }
        
        return true;
    }

    private void sendUnauthorized(HttpServletResponse response, String message) throws Exception {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write("{\"code\":401,\"message\":\"" + message + "\"}");
    }
}
