import { useCallback, useState } from 'react';
import { message } from 'antd';

function extractErrorMessage(err: unknown): string {
  if (err && typeof err === 'object' && 'response' in err) {
    const resp = (err as { response?: { data?: { message?: string } } }).response;
    return resp?.data?.message || '';
  }
  if (err instanceof Error) return err.message;
  return '';
}

interface UseApiRequestReturn {
  execute: <T>(fn: () => Promise<T>, successMsg?: string, errorMsg?: string) => Promise<T | null>;
  loading: boolean;
}

export function useApiRequest(): UseApiRequestReturn {
  const [loading, setLoading] = useState(false);

  const execute = useCallback(async <T>(
    fn: () => Promise<T>,
    successMsg?: string,
    errorMsg = '操作失败',
  ): Promise<T | null> => {
    setLoading(true);
    try {
      const result = await fn();
      if (successMsg) message.success(successMsg);
      return result;
    } catch (err) {
      const msg = extractErrorMessage(err);
      message.error(msg || errorMsg);
      return null;
    } finally {
      setLoading(false);
    }
  }, []);

  return { execute, loading };
}
