package com.qqchen.deploy.backend.framework.tenant;

import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.List;

//@Component
public class TenantInterceptor implements HandlerInterceptor {

    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    
    // 不需要进行租户隔离的路径
    private final List<String> excludePaths = Arrays.asList(
        "/api/v1/users/login",
        "/api/v1/tenant/list",
        "/swagger-ui/**",
        "/v3/api-docs/**"
    );

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();
        // 如果是白名单路径，不进行租户校验
        if (isExcludePath(path)) {
            TenantContext.clear();
            return true;
        }
        // 获取租户ID
        String tenantId = request.getHeader("X-Devops-Tenant-Id");
        if (tenantId == null || tenantId.trim().isEmpty()) {
            throw new BusinessException(ResponseCode.TENANT_NOT_FOUND);
        }
        TenantContext.setTenantId(tenantId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        TenantContext.clear();
    }

    private boolean isExcludePath(String path) {
        return excludePaths.stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, path));
    }
} 