import useSWR, { type SWRResponse } from "swr";
import { fetchJson } from "./apiClient";
import { ProviderConfigSchema, type ProviderConfig } from "./providerContract";

async function fetcher(url: string): Promise<ProviderConfig[]> {
  return fetchJson(
    url,
    ProviderConfigSchema.array(),
    undefined,
    (response) => `Failed to fetch ${url}: ${response.status}`,
  );
}

export function useProviders() {
  const response: SWRResponse<ProviderConfig[], Error> = useSWR<ProviderConfig[], Error>(
    "/api/providers",
    fetcher,
    {
      revalidateOnFocus: false,
      revalidateIfStale: false,
    },
  );

  return {
    providers: response.data ?? [],
    isLoading: response.isLoading,
    isError: response.error,
    mutate: response.mutate,
  };
}
