const cache = new Map()
const CACHE_TTL = 30000
const PENDING = new Map()

export const cachedRequest = async (key, requestFn, ttl = CACHE_TTL) => {
	const now = Date.now()
	const cached = cache.get(key)
	if (cached && now - cached.time < ttl) {
		return cached.data
	}

	if (PENDING.has(key)) {
		return PENDING.get(key)
	}

	const promise = requestFn().then(data => {
		cache.set(key, { data, time: Date.now() })
		PENDING.delete(key)
		return data
	}).catch(err => {
		PENDING.delete(key)
		throw err
	})

	PENDING.set(key, promise)
	return promise
}

export const clearCache = (key) => {
	if (key) {
		cache.delete(key)
	} else {
		cache.clear()
	}
}

export const getCacheKey = (prefix, params) => {
	return `${prefix}:${JSON.stringify(params || {})}`
}

export const createCachedRequest = (cachePrefix) => {
	return async (url, config = {}) => {
		const key = getCacheKey(cachePrefix || url, config.data)
		return cachedRequest(key, () => {
			if (typeof config.request === 'function') {
				return config.request(url, config)
			}
			return new Promise((resolve, reject) => {
				uni.request({
					url: url,
					method: config.method || 'POST',
					data: config.data || {},
					header: config.header || {},
					timeout: config.timeout || 15000,
					success: (res) => resolve(res.data),
					fail: (err) => reject(new Error(err.errMsg || '请求失败'))
				})
			})
		}, config.cacheTTL)
	}
}

export default {
  cachedRequest,
  clearCache,
  createCachedRequest
}
