package com.linearpast.minecraftmanager.interceptor;

import com.linearpast.minecraftmanager.exception.UnauthorizedException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class ApiKeyInterceptor implements HandlerInterceptor {

    @Value("${api.key}")
    private String apiKey;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 1. 优先检查 API Key（Header: X-API-Key 或 Query: apiKey）
        String reqApiKey = request.getHeader("X-API-Key");
        if (!StringUtils.hasText(reqApiKey)) {
            reqApiKey = request.getParameter("apiKey");
        }
        if (StringUtils.hasText(reqApiKey) && apiKey.equals(reqApiKey)) {
            return true;
        }

        // 2. 回退到 Session 鉴权（浏览器访问）
        HttpSession session = request.getSession();
        if (session != null
                && session.getAttribute("isLoggedIn") != null
                && (boolean) session.getAttribute("isLoggedIn")
                && session.getAttribute("adminAccount") != null) {
            return true;
        }

        throw new UnauthorizedException("redirect:/admin/login?error=please login first");
    }
}
