import { useCallback } from 'react' import type { MutationHookContext, HookFetcherContext, } from '@commerce/utils/types' import { ValidationError } from '@commerce/utils/errors' import useRemoveItem, { UseRemoveItem } from '@commerce/cart/use-remove-item' import type { Cart, LineItem, RemoveItemHook } from '@commerce/types/cart' import useCart from './use-cart' export type RemoveItemFn = T extends LineItem ? (input?: RemoveItemActionInput) => Promise : (input: RemoveItemActionInput) => Promise export type RemoveItemActionInput = T extends LineItem ? Partial : RemoveItemHook['actionInput'] export default useRemoveItem as UseRemoveItem export const handler = { fetchOptions: { url: '/api/cart', method: 'DELETE', }, async fetcher({ input: { itemId }, options, fetch, }: HookFetcherContext) { return await fetch({ ...options, body: { itemId } }) }, useHook: ({ fetch }: MutationHookContext) => (ctx: { item?: T } = {}) => { const { item } = ctx const { mutate } = useCart() const removeItem: RemoveItemFn = async (input) => { const itemId = input?.id ?? item?.id if (!itemId) { throw new ValidationError({ message: 'Invalid input used for this operation', }) } const data = await fetch({ input: { itemId } }) await mutate(data, false) return data } return useCallback(removeItem as RemoveItemFn, [fetch, mutate]) }, }