package com.ff.base.utils;

import com.ff.base.constant.Constants;
import com.ff.base.datasource.DynamicDataSourceContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 持有Utils
 *
 * @author shi
 * @date 2024/12/10
 */
public class TenantUtils {

    public static String getTenantId() {
        // 获取当前请求的 ServletRequestAttributes 对象
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attributes == null) {
            // 当前线程中无法获取请求上下文，返回默认数据源
            return Constants.DATA_SOURCE;
        }

        HttpServletRequest request = attributes.getRequest();

        // 从请求头中获取 tenantId
        String tenantId = request.getHeader(Constants.TENANT_ID);

        // 如果 tenantId 为空或缺失，返回默认数据源
        if (StringUtils.isEmpty(tenantId)) {
            return Constants.DATA_SOURCE;
        }
        // 返回有效的 tenantId
        return tenantId;

    }

    /**
     * 获取租户id redis
     *
     * @return {@link String }
     */
    public static String getTenantIdRedis(String key) {
        String dataSourceType = DynamicDataSourceContextHolder.getDataSourceType();
        dataSourceType = StringUtils.hasText(dataSourceType) ? dataSourceType : Constants.DATA_SOURCE;
        return dataSourceType.toLowerCase()+":"+key;

    }
}
