import { AsyncLocalStorage } from "node:async_hooks";
import type { TenantContext } from "@/core/tenant/types";

const tenantStorage = new AsyncLocalStorage<TenantContext>();

/**
 * Run a function with trusted TenantContext bound to the async call chain.
 */
export function runWithTenantContext<T>(
  context: TenantContext,
  fn: () => T,
): T {
  return tenantStorage.run(context, fn);
}

export function getTenantContext(): TenantContext | undefined {
  return tenantStorage.getStore();
}

/**
 * Require tenant context. Throws if missing.
 * Use in tenant-scoped services — never invent a fallback tenant.
 */
export function requireTenantContext(): TenantContext {
  const ctx = getTenantContext();
  if (!ctx) {
    throw new Error("TenantContext is required but was not established");
  }
  return ctx;
}
