package org.ssssssss.magicapi.plugin.simple.interceptor;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.magicapi.utils.IpUtils;
import org.ssssssss.script.MagicScriptContext;

/**
 *  接口IP白名单
 */
@Component
public class IpLimitRequestInterceptor implements RequestInterceptor {
    public final static String START_PLUGIN_LOG_MSG="已开启[{}],如需关闭[{}],插件配置信息:[{}]";
    private static final Logger log = LoggerFactory.getLogger(IpLimitRequestInterceptor.class);
    /**
     * 白名单
     */
    private String whitelist;
    /**
     * 黑名单
     */
    private String blacklist;

    @PostConstruct
    public void initIpLimitRequestInterceptor() {
        log.info(START_PLUGIN_LOG_MSG, "接口IP白名单", "magic-api.api-iplimit.enable=false", "magic-api.api-iplimit.whitelist=ip地址逗号分隔");
    }
    @Override
    public Object preHandle(ApiInfo info, MagicScriptContext context, MagicHttpServletRequest request, MagicHttpServletResponse response) throws Exception {
        String ip = IpUtils.getRealIP(request.getRemoteAddr(), request::getHeader, null);
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) {
            return true; // 直接放行回环地址
        }
        if (isIpInBlacklist(ip)) {
            return new JsonBean(100, String.format("IP:[%s] 访问URL:[%s] 被拒绝，位于黑名单中", ip, info.getPath()));
        }
        if (whitelist != null && !whitelist.isEmpty() && !whitelist.contains(ip)) {
            return new JsonBean(100, String.format("IP:[%s] 访问URL:[%s] 被拒绝，未在白名单中", ip, info.getPath()));
        }
        return RequestInterceptor.super.preHandle(info, context, request, response);
    }


    private boolean isIpInBlacklist(String ip) {
        return !blacklist.isEmpty() && blacklist.contains(ip);
    }


    public String getWhitelist() {
        return whitelist;
    }

    public void setWhitelist(String whitelist) {
        this.whitelist = whitelist;
    }

    public String getBlacklist() {
        return blacklist;
    }

    public void setBlacklist(String blacklist) {
        this.blacklist = blacklist;
    }
}

