import { AsyncLocalStorage } from 'node:async_hooks';
import type { Role } from '@prisma/client';

/**
 * Per-request tenant context, carried implicitly via AsyncLocalStorage so the
 * scoped Prisma client (see ./prisma.ts) can inject `tenantId` on every query
 * without any route handler having to remember to pass it.
 *
 * - SUPER_ADMIN has `tenantId: null` (platform staff, not bound to a tenant).
 *   Super-admin cross-tenant work uses the UNSCOPED client explicitly.
 */
export interface TenantContext {
  userId: string;
  role: Role;
  tenantId: string | null;
}

const storage = new AsyncLocalStorage<TenantContext>();

/** Run `fn` with the given tenant context bound for its entire async lifetime. */
export function runWithTenantContext<T>(ctx: TenantContext, fn: () => T): T {
  return storage.run(ctx, fn);
}

/** Current context, or undefined if called outside a bound request. */
export function getTenantContext(): TenantContext | undefined {
  return storage.getStore();
}

/**
 * The current tenantId, or throw. Use when creating rows on models whose
 * `tenantId` is non-nullable (the scoped client still overrides it, but
 * TypeScript needs it present and transactions may bypass the extension).
 */
export function getTenantIdOrThrow(): string {
  const ctx = storage.getStore();
  if (!ctx?.tenantId) {
    throw new Error('getTenantIdOrThrow called without a tenant context');
  }
  return ctx.tenantId;
}
