package com.ruoyi.framework.interceptor;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CorpContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 企业上下文拦截器
 * 在请求处理前从 Redis 获取当前企业ID并设置到 ThreadLocal
 * 在请求处理后清理 ThreadLocal
 */
@Component
public class CorpContextInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从 Redis 获取当前企业ID
        String corpId = redisCache.getCacheObject("current_corp_id");

        // 如果存在企业ID，设置到 ThreadLocal
        if (corpId != null && !corpId.trim().isEmpty()) {
            CorpContextHolder.setCurrentCorpId(corpId);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后清理 ThreadLocal，避免内存泄漏
        CorpContextHolder.clear();
    }
}
