import {useMemo} from 'react'

import {useShopActions} from '../../internal/useShopActions'
import {useShopActionsDataFetching} from '../../internal/useShopActionsDataFetching'
import {
  Content,
  ContentIdentifierInput,
  DataHookOptionsBase,
  DataHookReturnsBase,
} from '../../types'

export interface UseContentParams extends DataHookOptionsBase {
  /**
   * The identifiers of the content to fetch.
   */
  identifiers: ContentIdentifierInput | ContentIdentifierInput[]
}

interface UseContentReturns extends DataHookReturnsBase {
  /**
   * The content returned from the query.
   */
  content: Content[] | null
}

export const useContent = (params: UseContentParams): UseContentReturns => {
  const {getContent} = useShopActions()
  const {identifiers, skip = false, ...restParams} = params

  const {data, ...rest} = useShopActionsDataFetching(
    getContent,
    {
      identifiers,
      ...restParams,
    },
    {
      skip,
      hook: 'useContent',
    }
  )

  const content = useMemo(() => {
    return data ?? null
  }, [data])

  return {
    ...rest,
    content,
  }
}
