/**
 * 自动包裹异步操作为“飞行中操作”的 Hook
 *
 * 用法：
 * ```ts
 * const handleGenerate = usePendingOperation(async () => {
 *   // 原有异步逻辑
 * });
 * ```
 */

import { useEffect, useMemo, useRef } from 'react';
import { withPendingOperation } from '../utils/pendingOperations';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function usePendingOperation<T extends (...args: any[]) => Promise<unknown>>(fn: T): T {
  const fnRef = useRef(fn);
  useEffect(() => {
    fnRef.current = fn;
  }, [fn]);

  return useMemo(
    () =>
      (async (...args: Parameters<T>) => {
        return withPendingOperation(() => fnRef.current(...args));
      }) as T,
    [],
  );
}
