import { AsyncLocalStorage } from 'async_hooks';
import { TenantInfo } from '../interfaces/tenant-info.interface';

export class TenantContextService {
  private static storage = new AsyncLocalStorage<TenantInfo>();

  static run<T>(tenant: TenantInfo, fn: () => T): T {
    return this.storage.run(tenant, fn);
  }

  static getTenant(): TenantInfo | null {
    return this.storage.getStore() ?? null;
  }

  static getTenantOrThrow(): TenantInfo {
    const tenant = this.storage.getStore();
    if (!tenant) throw new Error('Tenant context not initialized');
    return tenant;
  }

  static getTenantId(): string {
    return this.getTenantOrThrow().tenantId;
  }

  static getSchemaName(): string {
    return this.getTenantOrThrow().schemaName;
  }
}
