import messages from '@/locale/index'

const REQUIRED_STRINGS = [
	['apiNotFound', 'API 接口不存在'],
	['apiServerBusy', 'API 服務器繁忙']
]

function repairLocaleBundles(bundle) {
	const output = { ...bundle }
	Object.keys(output).forEach((locale) => {
		if (!output[locale].common) output[locale].common = {}
		const common = output[locale].common
		REQUIRED_STRINGS.forEach(([key, fallback]) => {
			if (typeof common[key] !== 'string' || !common[key]) {
				console.warn(`[i18n] repair ${locale}.common.${key}`)
				common[key] = fallback
			}
		})
	})
	return output
}

function resolveInitialLocale() {
	const saved = uni.getStorageSync('language')
	let locale = saved || uni.getLocale()
	if (locale === 'auto') locale = uni.getLocale()
	return locale
}

const i18nOptions = {
	locale: resolveInitialLocale(),
	fallbackLocale: 'zh-cn',
	silentFallbackWarn: true,
	messages: repairLocaleBundles(messages)
}

// #ifndef VUE3
import VueI18n from 'vue-i18n'

export function createAppI18n(Vue) {
	Vue.use(VueI18n)
	return new VueI18n(i18nOptions)
}
// #endif

// #ifdef VUE3
import { createI18n } from 'vue-i18n'

export function createAppI18n() {
	return createI18n({
		legacy: false,
		...i18nOptions
	})
}
// #endif
