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

import com.muyu.cloud.common.many.datasource.holder.DynamicDataSourceHolder;
import com.muyu.cloud.common.many.datasource.role.DynamicDataSource;
import com.muyu.cloud.common.saas.contents.SaaSConstant;
import com.muyu.cloud.common.saas.exception.SaaSException;
import com.muyu.common.core.constant.SecurityConstants;
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 lombok.extern.log4j.Log4j2;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;


@Log4j2
public class SaaSInterceptor implements AsyncHandlerInterceptor {

    /**
     * 之前
     */
    @Override
    public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

//        SaaSConstant.SAAS_KEY
//        SecurityConstants.SAAS_KEY

        String SaaSKey = ServletUtils.getHeader(request, SaaSConstant.SAAS_KEY);
        if (SaaSKey == null || "".equals(SaaSKey)) {
            throw new SaaSException("SaaS非法访问");
        }else {
            DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
            if (!dynamicDataSource.hashKey(SaaSKey)){
                throw new SaaSException("SaaS非法访问");
            }
        }
        DynamicDataSourceHolder.setDynamicDataSourceKey(SaaSKey);
        log.info("SaaS拦截器拦截到请求，设置数据源为：{}", SaaSKey);
        return true;
    }

    /**
     * 之后
     */
    @Override
    public void afterConcurrentHandlingStarted (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        DynamicDataSourceHolder.removeDynamicDataSourceKey();
    }
}
