import { STORAGE } from '@/core/constants/storage-keys'

export const DEFAULT_CURRENCY = 'HKD'

export const CURRENCY_OPTIONS = Object.freeze([
	{ code: 'HKD', labelKey: 'user.currencyHKD' },
	{ code: 'CNY', labelKey: 'user.currencyCNY' },
	{ code: 'USD', labelKey: 'user.currencyUSD' },
	{ code: 'MOP', labelKey: 'user.currencyMOP' },
	{ code: 'TWD', labelKey: 'user.currencyTWD' }
])

export function isSupportedCurrency(code) {
	const next = String(code || '').trim().toUpperCase()
	return CURRENCY_OPTIONS.some((row) => row.code === next)
}

export function getStoredCurrency() {
	try {
		const raw = uni.getStorageSync(STORAGE.currency)
		const code = String(raw || '').trim().toUpperCase()
		if (isSupportedCurrency(code)) return code
	} catch (_) {}
	return DEFAULT_CURRENCY
}

export function setStoredCurrency(code) {
	const next = String(code || '').trim().toUpperCase()
	if (!isSupportedCurrency(next)) return false
	uni.setStorageSync(STORAGE.currency, next)
	return true
}

export function currencyLabelForCode(code, t) {
	const row = CURRENCY_OPTIONS.find((item) => item.code === String(code || '').toUpperCase())
	if (!row) return String(code || DEFAULT_CURRENCY)
	return t(row.labelKey)
}
