import { postBookmark, postUnBookmark } from 'src/lib/api'
import { emit } from 'src/lib/tapestry/emit'
import { postScopeKeys, useCacheMutation } from './cacheMutation'
import { updatePostInCache } from './updatePostInCache'

type BookmarkMutateType = {
  type: boolean
  id: string
}

export function useBookmarkMutation({
  onSuccess,
}: {
  onSuccess?: (data: any, variables: BookmarkMutateType) => void
} = {}) {
  const { mutate, isPending } = useCacheMutation<unknown, BookmarkMutateType>({
    mutationFn: ({ id, type }) => (type ? postBookmark(id) : postUnBookmark(id)),
    snapshotKeys: ({ id }) => postScopeKeys(id),
    applyOptimistic: (qc, { id, type }) => {
      updatePostInCache(qc, id, (post) => ({ ...post, bookmarked: type }))
    },
    onSuccess: (data, vars) => {
      if (vars.type) emit('B')
      onSuccess?.(data, vars)
    },
  })

  const handleBookmark = async (id: string, isBookmarked: boolean) => {
    try {
      await mutate({ id, type: isBookmarked })
    } catch (_err) {}
  }

  return { handleBookmark, isBookmarkPending: isPending }
}
