import type { Transaction } from 'sequelize';
import db from '@/db/models';

/**
 * Runs `fn` inside a managed Sequelize transaction: commits on success, rolls
 * back and rethrows on failure. Replaces the repeated begin/try/commit/rollback
 * boilerplate in the services.
 */
export async function withTransaction<T>(
  fn: (transaction: Transaction) => Promise<T>,
): Promise<T> {
  const transaction = await db.sequelize.transaction();
  try {
    const result = await fn(transaction);
    await transaction.commit();
    return result;
  } catch (error) {
    await transaction.rollback();
    throw error;
  }
}
