import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
import { api, type ListProvidersParams, type PaginatedResponse } from "@/lib/api";
import { useAppStore } from "@/store";
import type { Provider } from "@/types";

/**
 * Lists providers. Falls back to the in-memory zustand store when no
 * backend is configured; the store carries the full provider directory
 * so no pagination is applied in fallback mode.
 */
export function useProviders(params: ListProvidersParams = {}) {
  const fallback = useSyncExternalStore(
    (cb) => useAppStore.subscribe(cb),
    () => useAppStore.getState().providers,
    () => useAppStore.getState().providers
  );

  const q = useQuery<PaginatedResponse<Provider>>({
    queryKey: ["providers", params],
    queryFn: () => api.listProviders<Provider>(params),
    enabled: api.isConfigured,
  });

  if (!api.isConfigured) {
    return {
      data: {
        items: fallback,
        total: fallback.length,
        returned: fallback.length,
        has_more: false,
      } satisfies PaginatedResponse<Provider>,
      isLoading: false,
      isError: false,
      error: null,
      refetch: () => Promise.resolve(),
    } as const;
  }
  return q;
}
