package com.usky.vpp.config;

import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;

/**
 * 当前线程 UN 对接所使用的租户上下文
 */
public final class VppUnTenantContext {

    private static final ThreadLocal<Integer> TENANT_ID = new ThreadLocal<>();

    private VppUnTenantContext() {
    }

    public static void setTenantId(Integer tenantId) {
        TENANT_ID.set(tenantId);
    }

    public static Integer getTenantId() {
        return TENANT_ID.get();
    }

    /**
     * 解析当前租户 ID：定时任务等场景优先使用 {@link #runWithTenant} 传入的 tenantId；
     * 接口调用场景使用 {@link SecurityUtils#getTenantId()}。
     */
    public static Integer resolveTenantId() {
        Integer tenantId = TENANT_ID.get();
        if (tenantId != null) {
            return tenantId;
        }
        tenantId = SecurityUtils.getTenantId();
        if (tenantId != null && tenantId > 0) {
            return tenantId;
        }
        throw new BusinessException("缺少租户上下文，无法获取运管平台配置租户Id");
    }

    public static void clear() {
        TENANT_ID.remove();
    }

    public static void runWithTenant(Integer tenantId, Runnable action) {
        setTenantId(tenantId);
        try {
            action.run();
        } finally {
            clear();
        }
    }

    public static <T> T callWithTenant(Integer tenantId, java.util.function.Supplier<T> action) {
        setTenantId(tenantId);
        try {
            return action.get();
        } finally {
            clear();
        }
    }
}
