import {useCallback} from 'react'

import {ShopActionResult} from '@shopify/shop-minis-platform/actions'

// Wrapper to handle shop action results as regular promises (Reject on error)
export const useHandleAction = <T, Args extends unknown[]>(
  action: (...args: Args) => Promise<ShopActionResult<T>>
) => {
  // TODO Add when report interaction is implemented for web
  // const reportInteraction = useReportInteraction()

  return useCallback(
    (...args: Args) => {
      return action(...args).then(result => {
        if (result.ok) {
          return result.data
        }

        throw result.error
      })
    },
    [action]
  )
}
