import { useCallback, useState } from "react";
import { apiRequest } from "../lib/api-client";

type ApiState<T> = {
  data: T | null;
  error: string | null;
  isLoading: boolean;
};

export function useApi<T>() {
  const [state, setState] = useState<ApiState<T>>({
    data: null,
    error: null,
    isLoading: false,
  });

  const execute = useCallback(async (path: string, options?: RequestInit) => {
    setState((prev) => ({ ...prev, isLoading: true, error: null }));
    try {
      const data = await apiRequest<T>(path, options);
      setState({ data, error: null, isLoading: false });
      return data;
    } catch (err) {
      const error = err instanceof Error ? err.message : "Unknown error";
      setState({ data: null, error, isLoading: false });
      throw err;
    }
  }, []);

  return { ...state, execute };
}
