import { reactive, ref, toRefs, watchEffect } from 'vue'
import { useI18n, UseI18nOptions } from 'vue-i18n'

type OptionalLastN<
  T extends any[],
  N extends number,
  Acc extends any[] = [],
> = T['length'] extends N
  ? [...T, ...Acc]
  : T extends [...infer Rest, infer Last]
  ? OptionalLastN<Rest, N, [Last?, ...Acc]>
  : Acc

export function useStoreI18n(options?: UseI18nOptions) {
  const { t, locale } = useI18n(options)

  const keyMap = reactive<Record<string, string>>({})
  function $t(...[key, ...options]: OptionalLastN<Parameters<typeof t>, 1>) {
    watchEffect(() => {
      if (locale.value) keyMap[key] = t(key, ...options)
    })
    return toRefs(keyMap)[key]
  }
  return {
    $t,
  }
}
