import { Knex } from 'knex';
import db from '../../config/database';
import { logger } from '../../utils/logger';

/**
 * [CORE_SEC_45] 租户数据主权隔离门禁 (Grounding Implementation)
 * @description 核心逻辑：提供基于租户 ID 的数据隔离拦截器，确保所有查询必须携带 tenant_id
 */
export class MultiTenantCore {
  /**
   * 获取受限的数据库查询构造器
   * @param tenantId 租户 ID
   * @param tableName 表名
   * @returns 带有 tenant_id 过滤条件的 Knex QueryBuilder
   */
  static from(tenantId: string, tableName: string): Knex.QueryBuilder {
    if (!tenantId) {
      throw new Error('[MultiTenantCore] tenant_id is required for data isolation gate');
    }

    // 记录隔离审计日志 (仅限 Debug)
    logger.info(`[IsolationGate] Querying ${tableName} for Tenant: ${tenantId}`);

    return db(tableName).where({ tenant_id: tenantId });
  }

  /**
   * 强制执行数据主权校验 (用于 Update/Delete 等关键操作)
   * @param tenantId 租户 ID
   * @param tableName 表名
   * @param id 数据记录 ID
   */
  static async ensureOwnership(tenantId: string, tableName: string, id: string | number): Promise<boolean> {
    const record = await db(tableName)
      .where({ id, tenant_id: tenantId })
      .first();
    
    if (!record) {
      logger.error(`[IsolationGate] SECURITY ALERT: Tenant ${tenantId} attempted to access unauthorized record ${id} in ${tableName}`);
      return false;
    }
    return true;
  }

  /**
   * 包装事务以支持租户隔离
   */
  static async transaction(tenantId: string, callback: (trx: Knex.Transaction) => Promise<void>) {
    return db.transaction(async (trx) => {
      // 在事务中也可以通过此 context 确保安全
      await callback(trx);
    });
  }
}
