// Wraps the dominant admin-handler mutation pattern:
//   try { await fn(); pushToast(success?); }
//   catch (e) { pushToast(errMessage(e), 'error'); }
//
// Errors are SWALLOWED — caller does not need a try/catch. Any
// `saving = true / saving = false` state flag can sit around the
// `await runMutation(...)` call without try/finally because the
// helper never rethrows.
//
// Use ONLY for handlers that surface errMessage(e) directly.
// Handlers that branch on specific error codes (last_admin,
// password_too_short) or build custom copy with errCode keep
// their inline catch — wrapping those would obscure intent.

import { errMessage } from '$lib/api/errors';
import { pushToast } from '$lib/stores/toast.svelte';

export async function runMutation(
  fn: () => Promise<unknown>,
  opts: { successMessage?: string } = {}
): Promise<void> {
  try {
    await fn();
    if (opts.successMessage) pushToast(opts.successMessage);
  } catch (e) {
    pushToast(errMessage(e), 'error');
  }
}
