package com.erp.tenant.config;

import com.erp.tenant.entity.Tenant;
import com.erp.tenant.repository.TenantRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Optional;

/**
 * 多租户上下文过滤器
 * 
 * 从请求中提取租户信息并设置到ThreadLocal中
 */
@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class TenantContextFilter extends OncePerRequestFilter {
    
    public static final String HEADER_TENANT_ID = "X-Tenant-Id";
    public static final String HEADER_TENANT_CODE = "X-Tenant-Code";
    
    private final TenantRepository tenantRepository;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            // 从请求头获取租户标识
            String tenantIdHeader = request.getHeader(HEADER_TENANT_ID);
            String tenantCodeHeader = request.getHeader(HEADER_TENANT_CODE);
            
            TenantContext.setCurrentTenant(null); // 默认无租户上下文
            
            if (tenantIdHeader != null || tenantCodeHeader != null) {
                Tenant tenant = resolveTenant(tenantIdHeader, tenantCodeHeader);
                if (tenant != null) {
                    TenantContext.setCurrentTenant(tenant);
                    log.debug("设置租户上下文: id={}, code={}", tenant.getId(), tenant.getCode());
                }
            }
            
            filterChain.doFilter(request, response);
        } finally {
            TenantContext.clear();
        }
    }
    
    private Tenant resolveTenant(String tenantIdHeader, String tenantCodeHeader) {
        if (tenantIdHeader != null) {
            try {
                Long tenantId = Long.parseLong(tenantIdHeader);
                return tenantRepository.selectById(tenantId);
            } catch (NumberFormatException e) {
                log.warn("无效的租户ID: {}", tenantIdHeader);
            }
        }
        
        if (tenantCodeHeader != null) {
            return tenantRepository.findByCode(tenantCodeHeader);
        }
        
        return null;
    }
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        // 忽略健康检查等路径
        String path = request.getRequestURI();
        return path.startsWith("/actuator") || 
               path.startsWith("/swagger") || 
               path.startsWith("/v3/api-docs");
    }
}
