package com.dora.config;

import com.dora.entity.User;
import com.dora.service.ApiKeyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * API密钥验证拦截器
 */
@Component
public class ApiKeyInterceptor implements HandlerInterceptor {

    @Autowired
    private ApiKeyService apiKeyService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的API密钥
        String apiKey = request.getHeader("X-API-Key");
        
        if (apiKey == null || apiKey.trim().isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"API密钥不能为空\"}");
            return false;
        }

        // 验证API密钥
        User user = apiKeyService.validateApiKey(apiKey);
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"API密钥无效或已过期\"}");
            return false;
        }

        // 将用户信息存储到请求属性中，供后续使用
        request.setAttribute("currentUser", user);
        
        return true;
    }
} 