package com.ycwl.basic.puzzle.edge.interceptor;

import com.ycwl.basic.puzzle.edge.config.PuzzleEdgeWorkerSecurityProperties;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.IpUtils;
import com.ycwl.basic.utils.Ipv4CidrMatcher;
import com.ycwl.basic.utils.JacksonUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 边缘 Worker 接口访问 IP 校验
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PuzzleEdgeWorkerIpInterceptor implements HandlerInterceptor {

    private static final String FORBIDDEN_MESSAGE = "非法来源IP";

    private final PuzzleEdgeWorkerSecurityProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (properties == null || !properties.isEnabled()) {
            return true;
        }

        String clientIp = IpUtils.getIpAddr(request);
        if (Ipv4CidrMatcher.matches(clientIp, properties.getAllowedIpCidr())) {
            return true;
        }
        if (Ipv4CidrMatcher.matches(clientIp, "127.0.0.1/8")) {
            return true;
        }

        log.warn("拒绝边缘 Worker 请求: uri={}, ip={}, allowedIpCidr={}",
                request != null ? request.getRequestURI() : null,
                clientIp,
                properties.getAllowedIpCidr());

        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JacksonUtil.toJson(ApiResponse.buildResponse(HttpStatus.FORBIDDEN.value(), FORBIDDEN_MESSAGE)));
        return false;
    }
}

