import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  listSavedQueries,
  saveQuery,
  deleteSavedQuery,
} from "@/lib/tauri";
import type { SavedQuery } from "@/types";

export function useSavedQueries(search?: string) {
  return useQuery({
    queryKey: ["saved-queries", search],
    queryFn: () => listSavedQueries({ search }),
  });
}

export function useSaveQuery() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (query: SavedQuery) => saveQuery(query),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["saved-queries"] });
    },
  });
}

export function useDeleteSavedQuery() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deleteSavedQuery(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["saved-queries"] });
    },
  });
}
