import { createAsyncContext } from './AsyncContext.js';
/** Uses `AsyncLocalStorage` to maintain a transaction-scoped EntityManager context across async operations. */
export class TransactionContext {
  em;
  static storage = createAsyncContext();
  id;
  constructor(em) {
    this.em = em;
    this.id = this.em._id;
  }
  /**
   * Creates new TransactionContext instance and runs the code inside its domain.
   */
  static create(em, next) {
    const context = new TransactionContext(em);
    return this.storage.run(context, next);
  }
  /**
   * Returns current TransactionContext (if available).
   */
  static currentTransactionContext() {
    return this.storage.getStore();
  }
  /**
   * Returns current EntityManager (if available).
   */
  static getEntityManager(name = 'default') {
    const context = TransactionContext.currentTransactionContext();
    return context?.em.name === name ? context.em : undefined;
  }
}
