import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  getAiSettings,
  saveAiSettings,
  listOllamaModels,
  listFireworksModels,
  listOpenRouterModels,
} from "@/lib/tauri";
import type { AiSettings } from "@/types";

export function useAiSettings() {
  return useQuery({
    queryKey: ["ai-settings"],
    queryFn: getAiSettings,
    staleTime: Infinity,
  });
}

export function useSaveAiSettings() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (settings: AiSettings) => saveAiSettings(settings),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["ai-settings"] });
    },
  });
}

export function useOllamaModels(ollamaUrl: string | undefined) {
  return useQuery({
    queryKey: ["ollama-models", ollamaUrl],
    queryFn: () => listOllamaModels(ollamaUrl!),
    enabled: !!ollamaUrl,
    retry: false,
  });
}

export function useFireworksModels(apiKey: string | undefined) {
  return useQuery({
    queryKey: ["fireworks-models", apiKey],
    queryFn: () => listFireworksModels(apiKey!),
    enabled: !!apiKey && apiKey.trim().length > 0,
    retry: false,
    staleTime: 60_000,
  });
}

export function useOpenRouterModels(apiKey: string | undefined) {
  return useQuery({
    queryKey: ["openrouter-models", apiKey],
    queryFn: () => listOpenRouterModels(apiKey!),
    enabled: !!apiKey && apiKey.trim().length > 0,
    retry: false,
    staleTime: 60_000,
  });
}
