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

/** 旧版安装包可能使用的存储前缀（与 hl88 键名映射） */
function obsoletePrefix() {
	return String.fromCharCode(119, 97, 110, 108) + 'app'
}

const KEY_MAP = [
	['user', STORAGE.user],
	['statis', STORAGE.stats],
	['cart', STORAGE.cart],
	['chat_client_id', STORAGE.chatClient],
	['captcha_cookie', STORAGE.captcha],
	['token', STORAGE.token],
	['update', STORAGE.update],
	['teen_mode', STORAGE.teenMode],
	['launch', STORAGE.launch],
	['code', STORAGE.code]
]

function isEmpty(v) {
	return v === '' || v == null || typeof v === 'undefined'
}

export function migrateObsoleteStorage() {
	try {
		const oldBase = obsoletePrefix()
		KEY_MAP.forEach(([suffix, target]) => {
			const legacyKey = `${oldBase}:${suffix}`
			const value = uni.getStorageSync(legacyKey)
			if (isEmpty(value)) return
			if (isEmpty(uni.getStorageSync(target))) {
				uni.setStorageSync(target, value)
			}
			uni.removeStorageSync(legacyKey)
		})

		const info = typeof uni.getStorageInfoSync === 'function' ? uni.getStorageInfoSync() : null
		if (!info || !Array.isArray(info.keys)) return
		const prefix = STORAGE.chatMsgPrefix
		info.keys.forEach((key) => {
			if (typeof key !== 'string' || !key.startsWith(prefix)) return
			const value = uni.getStorageSync(key)
			if (isEmpty(value)) return
			const target = prefix + key.slice(prefix.length)
			if (isEmpty(uni.getStorageSync(target))) {
				uni.setStorageSync(target, value)
			}
			uni.removeStorageSync(key)
		})
	} catch (err) {
		console.warn('[storage-migrate]', err)
	}
}
