package com.muyu.cloud.common.saas.interceptor;

import com.muyu.cloud.common.saas.contents.SaaSConstant;
import com.muyu.cloud.common.many.datasource.holder.DynamicDataSourceHolder;
import com.muyu.cloud.common.saas.exception.SaaSException;
import com.muyu.cloud.common.many.datasource.role.DynamicDataSource;
import com.muyu.common.core.utils.ServletUtils;
import com.muyu.common.core.utils.SpringUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

/**
 * @Author: zi run
 * @Date 2024/9/20 19:41
 * @Description SAAS拦截器
 */
public class SaaSInterceptor implements AsyncHandlerInterceptor {

    /**
     * 请求执行之前触发
     * @param request servlet请求对象
     * @param response servlet响应对象
     * @param handler 处理器
     * @return 是否放行
     * @throws Exception 可能抛出的异常
     */
    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        String SaaSKey = ServletUtils.getHeader(request, SaaSConstant.SAAS_KEY);
        if (SaaSKey == null) {
            throw new SaaSException("SaaS非法访问");
        }else {
            DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
            if (!dynamicDataSource.hashKey(SaaSKey)){
                throw new SaaSException("SaaS非法访问");
            }
        }
        DynamicDataSourceHolder.setDynamicDataSourceKey(SaaSKey);
        return true;
    }

    /**
     * 请求执行之后触发
     * @param request servlet请求对象
     * @param response servlet响应对象
     * @param handler 处理器
     * @throws Exception servlet响应对象
     */
    @Override
    public void afterConcurrentHandlingStarted (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        DynamicDataSourceHolder.removeDynamicDataSourceKey();
    }
}
