import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { fetchKeywords, addKeyword, updateKeyword, deleteKeyword, reorderKeywords } from '@/lib/api/keywords'

const KEY = ['keywords']

export const useKeywords = () => useQuery({ queryKey: KEY, queryFn: fetchKeywords })

export const useAddKeyword = () => {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ term, weight }: { term: string; weight: number }) => addKeyword(term, weight),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY })
  })
}

export const useUpdateKeyword = () => {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Parameters<typeof updateKeyword>[1] }) => updateKeyword(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: KEY })
  })
}

export const useDeleteKeyword = () => {
  const qc = useQueryClient()
  return useMutation({ mutationFn: deleteKeyword, onSuccess: () => qc.invalidateQueries({ queryKey: KEY }) })
}

export const useReorderKeywords = () => {
  const qc = useQueryClient()
  return useMutation({ mutationFn: reorderKeywords, onSuccess: () => qc.invalidateQueries({ queryKey: KEY }) })
}
