import {useCallback} from 'react'

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

import {getWindowLocationPathname} from '../utils/getWindowLocationPathname'

import {useHandleAction} from './useHandleAction'
import {useShopActions} from './useShopActions'

interface UseReportImpressionReturns {
  /**
   * Report an impression event for analytics.
   */
  reportImpression: (params: ReportImpressionParams) => Promise<void>
}

export const useReportImpression = (): UseReportImpressionReturns => {
  const {reportImpression} = useShopActions()
  const handleAction = useHandleAction(reportImpression)

  const report = useCallback(
    (params: ReportImpressionParams) => {
      const enrichedParams = {
        ...params,
        pageValue: params.pageValue || getWindowLocationPathname(),
      }
      return handleAction(enrichedParams)
    },
    [handleAction]
  )

  return {reportImpression: report}
}
