// hooks/useRequest.ts
import { useState, useCallback } from "react";
import { message } from "antd";

export interface UseRequestOptions<T> {
  onSuccess?: (data: T) => void;
  onError?: (error: any) => void;
  showErrorMessage?: boolean;
}

export function useRequest<T = any, P = any>(
  requestFn: (params: P) => Promise<T>,
  options: UseRequestOptions<T> = {}
) {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<any>(null);

  const { onSuccess, onError, showErrorMessage = true } = options;

  const run = useCallback(
    async (params: P) => {
      setLoading(true);
      setError(null);

      try {
        const result = await requestFn(params);
        setData(result);
        onSuccess?.(result);
        return result;
      } catch (err) {
        setError(err);
        onError?.(err);
        if (showErrorMessage) {
          message.error("请求失败");
        }
        throw err;
      } finally {
        setLoading(false);
      }
    },
    [requestFn, onSuccess, onError, showErrorMessage]
  );

  return {
    loading,
    data,
    error,
    run,
  };
}
