package com.cf.imes.framework.web.core.filter;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.cf.imes.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.util.servlet.ServletUtils;
import com.cf.imes.framework.web.config.WebProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author there
 * 多数据源过滤器
 */
@Slf4j
public class DataSourceFilter extends OncePerRequestFilter {
    //数据源编码
    private static final String DATA_SOURCE_CODE = "data-code";
    /**
     * HEADER 认证头 value 的前缀
     */
    public static final String AUTHORIZATION_BEARER = "Bearer";


    private WebProperties webProperties;

    public DataSourceFilter (WebProperties webProperties) {
        this.webProperties = webProperties;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 只过滤 API 请求的地址
        return !StrUtil.startWithAny(request.getRequestURI(), webProperties.getAdminApi().getPrefix(),
                webProperties.getAppApi().getPrefix());
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String dataCode = request.getHeader(DATA_SOURCE_CODE);
        if(StrUtil.isEmpty(dataCode)) {
            //TODO 如果要严谨一点，应该再去校验一下token
            ServletUtils.writeJSON(response, CommonResult.error(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "访问令牌已过期"));
            log.info("Let the user log in because there is no data-code! requestURI==>{}", request.getRequestURI());
            return;
        }
        DynamicDataSourceContextHolder.push(dataCode);
        filterChain.doFilter(request, response);
        DynamicDataSourceContextHolder.clear();
    }


}
