import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { getAllBooks, searchBook } from "@/api/books"
import { borrowBookForMe } from "@/api/borrows"
import { toast } from "sonner"
import { getErrorMessage } from "@/lib/errors"

export function useBooks() {
  return useQuery({
    queryKey: ["books"],
    queryFn: getAllBooks,
    staleTime: 30_000,
  })
}

export function useSearchBooks(query: string) {
  return useQuery({
    queryKey: ["books", "search", query],
    queryFn: () => searchBook(query),
    enabled: query.length > 0,
    retry: false,
  })
}

export function useBorrowBook() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: borrowBookForMe,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["books"] })
      qc.invalidateQueries({ queryKey: ["myBorrows"] })
      toast.success("借阅成功")
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, "借阅失败"))
    },
  })
}
