import isArray from 'lodash/isArray'
import entries from 'lodash/entries'
import reduce from 'lodash/reduce'
import uniq from 'lodash/uniq'
import map from 'lodash/map'

import type { Translations } from 'requests'

import type { LexicsId, LexicsConfig } from '../types'

export const getSuffix = (lang: string) => (
  lang === 'ru' ? 'rus' : 'eng'
)

export const getShortSuffix = (lang: string) => (
  lang === 'ru' ? 'ru' : 'en'
)

export const getLexicIds = (ids: Array<LexicsId> | LexicsConfig) => (
  uniq(map(ids, (id) => Number(id)))
)

export const getObjectConfig = (ids: Array<LexicsId> | LexicsConfig) => {
  if (isArray(ids)) {
    return reduce(
      ids,
      (acc, id) => ({ ...acc, [id]: id }),
      {},
    )
  }
  return ids
}

export const mapTranslationsToLocalKeys = (
  translations: Translations,
  lexicsConfig: LexicsConfig,
) => {
  const pairs = entries(lexicsConfig)
  return reduce(
    pairs,
    (acc, [key, id]) => {
      if (translations[id]) {
        acc[key] = translations[id]
      }
      return acc
    },
    {} as Translations,
  )
}
