import { useCallback } from 'react' import type { MutationHookContext, HookFetcherContext, } from '@commerce/utils/types' import { ValidationError } from '@commerce/utils/errors' import useRemoveItem, { RemoveItemInput as RemoveItemInputBase, UseRemoveItem, } from '@commerce/cart/use-remove-item' import useCart from './use-cart' import { checkoutLineItemRemoveMutation, getCheckoutId } from '@framework/utils' import { checkoutToCart } from './utils' import { Cart, LineItem } from '@framework/types' import { Mutation, MutationCheckoutLineItemsRemoveArgs, } from '@framework/schema' import { RemoveCartItemBody } from '@commerce/types' export type RemoveItemFn = T extends LineItem ? (input?: RemoveItemInput) => Promise : (input: RemoveItemInput) => Promise export type RemoveItemInput = T extends LineItem ? Partial : RemoveItemInputBase export default useRemoveItem as UseRemoveItem export const handler = { fetchOptions: { query: checkoutLineItemRemoveMutation, }, async fetcher({ input: { itemId }, options, fetch, }: HookFetcherContext) { const data = await fetch({ ...options, variables: { checkoutId: getCheckoutId(), lineItemIds: [itemId] }, }) return checkoutToCart(data.checkoutLineItemsRemove) }, useHook: ({ fetch, }: MutationHookContext) => < T extends LineItem | undefined = undefined >( 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]) }, }