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

const MEMO_KEY = '__feed_list_memo__'
const DISK_KEY = STORAGE.feedList || 'hl88app:feed_list'
const TTL_MS = 5 * 60 * 1000
const MAX_PAGES = 8

/** 进程内分页缓存 */
const memo = {
	pages: new Map(),
	updatedAt: 0
}

function pageKey(page) {
	return `p${Number(page) || 1}`
}

function fresh(ts) {
	return Date.now() - ts < TTL_MS
}

export function readFeedPage(page) {
	const key = pageKey(page)
	const hit = memo.pages.get(key)
	if (hit && fresh(hit.ts)) {
		return { ...hit.data, fromCache: true }
	}
	try {
		const disk = uni.getStorageSync(DISK_KEY)
		if (!disk || !disk.pages) return null
		const row = disk.pages[key]
		if (row && fresh(row.ts)) {
			memo.pages.set(key, row)
			return { ...row.data, fromCache: true }
		}
	} catch (_) {}
	return null
}

export function writeFeedPage(page, pack) {
	const key = pageKey(page)
	const row = { ts: Date.now(), data: pack }
	memo.pages.set(key, row)
	memo.updatedAt = Date.now()

	const keys = [...memo.pages.keys()]
	if (keys.length > MAX_PAGES) {
		const drop = keys.sort((a, b) => {
			const ta = memo.pages.get(a)?.ts || 0
			const tb = memo.pages.get(b)?.ts || 0
			return ta - tb
		})[0]
		if (drop) memo.pages.delete(drop)
	}

	try {
		const disk = uni.getStorageSync(DISK_KEY) || { pages: {} }
		disk.pages = disk.pages || {}
		disk.pages[key] = row
		const diskKeys = Object.keys(disk.pages)
		if (diskKeys.length > MAX_PAGES) {
			const oldest = diskKeys.sort(
				(a, b) => (disk.pages[a]?.ts || 0) - (disk.pages[b]?.ts || 0)
			)[0]
			delete disk.pages[oldest]
		}
		disk.updatedAt = Date.now()
		uni.setStorageSync(DISK_KEY, disk)
	} catch (_) {}
}

export function clearFeedListCache() {
	memo.pages.clear()
	memo.updatedAt = 0
	try {
		uni.removeStorageSync(DISK_KEY)
	} catch (_) {}
}
