package com.storlead.framework.mybatis.tenant;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.storlead.framework.core.tenant.TenantContext;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

/**
 * MyBatis-Plus 3.1.x {@link com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser} 使用的租户解析器。
 * <p>
 * {@link TenantHandler#doTableFilter(String)} 返回 true 表示跳过租户条件；仅白名单表返回 false。
 * </p>
 */
public class StorleadTenantHandler implements TenantHandler {

    private final TenantProperties properties;

    public StorleadTenantHandler(TenantProperties properties) {
        this.properties = properties;
    }

    @Override
    public Expression getTenantId() {
        if (TenantContext.isIgnoreTenantLine()) {
            return null;
        }
        Long id = TenantContext.getTenantId();
        if (id == null) {
            return null;
        }
        return new LongValue(String.valueOf(id));
    }

    @Override
    public String getTenantIdColumn() {
        return properties.getColumnName();
    }

    @Override
    public boolean doTableFilter(String tableName) {
        return !properties.shouldApplyTenantLine(tableName);
    }
}
