import { createI18n } from 'vue-i18n'

function loadLocaleMessages() {
  const locales = import.meta.glob('../../i18n/locales/**/*.json', { eager: true })
  const messages: Record<string, any> = {}

  for (const path in locales) {
    const matched = path.match(/i18n\/locales\/(\w+)\/(.*)\.json$/)
    if (!matched) continue

    const [, locale, file] = matched

    if (!messages[locale]) {
      messages[locale] = {}
    }

    messages[locale][file] = (locales[path] as any).default
  }

  return messages
}

export default defineNuxtPlugin((nuxtApp) => {
  const i18n = createI18n({
    legacy: false,
    locale: 'en',
    messages: loadLocaleMessages()
  })

  nuxtApp.vueApp.use(i18n)
})