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

import com.alibaba.fastjson2.JSONObject;
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.context.SecurityContextHolder;
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.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;


/**
 * @Author: DongZeLiang
 * @date: 2024/6/3
 * @Description: SAAS拦截器
 * @Version: 1.0
 */
@Slf4j
public class SaaSInterceptor implements AsyncHandlerInterceptor {

    /**
     * 之前
     */
    @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);
        log.info("访问路径：{}，携带SaaSKey：{}",request.getRequestURI(),saasKey);
        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;
    }

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