package com.storlead.framework.web.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.storlead.framework.common.util.SystemUtils;
import com.storlead.framework.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2025-07-31 15:11
 */
@Log4j2
@Component
public class RoutingRequestFilter implements Filter, Ordered {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().equals("/api/router/rest")) {
            String code = request.getHeader("method");
            if (StrUtil.isBlank(code)) {
                Result result1 = Result.error("missing 'method' header");
                response.setStatus(HttpStatus.OK.value());
                SystemUtils.printJson(response, JSON.toJSONString(result1));
                return;
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public int getOrder() {
        return -95;
    }
}
