import type { App } from 'vue'
import type { I18n, I18nOptions } from 'vue-i18n'
import { createI18n } from 'vue-i18n'
import dayjs from 'dayjs'
import dayjsLocalizedFormat from 'dayjs/plugin/localizedFormat'
import dayjsZh from 'dayjs/locale/zh-cn'
import langs from './lang'

dayjs.extend(dayjsLocalizedFormat)
dayjs.locale(dayjsZh)

// eslint-disable-next-line import/no-mutable-exports
export let i18n: ReturnType<typeof createI18n>

function createI18nOptions(): I18nOptions {
    const locale = uni.getLocale() || 'zh-Hans'
    const defaultLocal = langs[locale]
    const message = defaultLocal?.message ?? {}

    return {
        locale,
        messages: {
            [locale]: message,
        },
        sync: true,
        legacy: false,
        missingWarn: false,
        globalInjection: true,
        silentFallbackWarn: true,
        silentTranslationWarn: true,
    }
}

// setup i18n instance with glob
export function setupI18n(app: App) {
    const options = createI18nOptions()
    i18n = createI18n(options) as I18n
    app.use(i18n)
}
