import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { getAllMyBorrows, searchMyBorrows, returnBookForMe } from "@/api/borrows"
import { toast } from "sonner"
import { getErrorMessage } from "@/lib/errors"

export function useMyBorrows() {
  return useQuery({
    queryKey: ["myBorrows"],
    queryFn: getAllMyBorrows,
  })
}

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

export function useReturnBook() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: returnBookForMe,
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["myBorrows"] })
      toast.success("归还成功")
    },
    onError: (err) => {
      toast.error(getErrorMessage(err, "归还失败"))
    },
  })
}
