/**
 * Wraps an async function to ensure only one execution runs at a time.
 * Subsequent calls while the first is running will return the same promise.
 * This is useful for store actions that fetch data to prevent duplicate requests.
 */
export function createSharedFetch<T extends (...args: any[]) => Promise<any>>(fn: T): T {
  let promise: Promise<ReturnType<T>> | null = null

  return function (this: any, ...args: Parameters<T>) {
    if (promise) return promise as ReturnType<T>

    promise = fn.apply(this, args).finally(() => {
      promise = null
    }) as Promise<ReturnType<T>>

    return promise as ReturnType<T>
  } as unknown as T
}
