import { useCallback } from 'react'

import isEmpty from 'lodash/isEmpty'
import flatMap from 'lodash/flatMap'
import uniq from 'lodash/uniq'

import type { Subscriptions } from 'requests/getSubscriptions'

import { useLexicsStore } from 'features/LexicsStore'

export const useSubscriptionsLexics = () => {
  const { addLexicsConfig } = useLexicsStore()

  const fetchLexics = useCallback((data: Subscriptions) => {
    const lexics = uniq(flatMap(data, ({
      lexic,
      lexic2,
      lexic3,
    }) => [lexic, lexic2, lexic3]))

    if (!isEmpty(lexics)) {
      addLexicsConfig(lexics)
    }

    return data
  }, [addLexicsConfig])

  return { fetchLexics }
}
